这是第二关的实现.
题目描述:
![]()
如图,要求就是找出对应的密码
分析:
随便输入,然后用开发者工具查看,有一条post的请求:
点进去:
可以看到 表单数据(Form Data)包含了cookie和用户名,密码,点击 view source,得到编码的字符串(虽然此post请求包含cookies,但服务器实际上用不着,只是cookies机制的问题)
csrfmiddlewaretoken=QkxgqDeP31SuohDsx63vU0zZP7fIIcCv&username=1&password=1
知道了原理,就明白,我们要用urllib模块,在urlopen里添加data参数,这样就会以post方法请求url.接着用这则抓取返回的html中密码错误 字样,如果抓取失败,那说明当前页面就是验证成功的页面.
实现:
import urllib.parse
import urllib.request
import re
data={'username':'hailong'}
url='http://www.heibanke.com/lesson/crawler_ex01/'
for num in range(1,31):
data['password']=num
post_data=urllib.parse.urlencode(data).encode('utf-8')
print(post_data)
response=urllib.request.urlopen(url,post_data)
html=response.read().decode('utf-8')
result=re.findall('密码错误',html)
if not result:
print(html)
break