《精通python网络爬虫》学习笔记三

Cookie

Cookiejar

先通过F12,点击登录按钮找到post方法对应的request url。然后在网页源码中找到表单的name。
先进行无Cookie的登录

url = "....."  #登录网址
postdata = urllib.parse.urlencode({
"username":"....",
"password":"...."
}).encode('utf-8')
req = urllib.request.Request(url, postdata)
req.add_header('User-Agent', '.....')
data = urllib.request.urlopen(req).read()

这里会爬到登录之后跳转的页面

接下来进行有Cookie的登录并爬取登录后的首页

import http.cookiejar
...#同上
cjar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar)) #使用HTTPCookieProcessor创建cookie处理器
urllib.request.install_opener(opener) #将opener安装为全局
file = opener.open(req)

猜你喜欢

转载自blog.csdn.net/sinat_25721683/article/details/81116496