import urllib.request
import urllib.parse
# 让代码保存cookie
import http.cookiejar
# 创建一个cookiejar对象,用来保存cookie
ck = http.cookiejar.CookieJar()
# 根据cookiejar对象创建一个handler
handler = urllib.request.HTTPCookieProcessor(ck)
# 根据handler创建opener
opener = urllib.request.build_opener(handler)
# 再往下所有的请求都使用opener.open()方法发送,那么cookie就会自动携带
post_url = 'url1'
data = {}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
}
data = urllib.parse.urlencode(data).encode("utf8")
request = urllib.request.Request(url=post_url, headers=headers)
response = opener.open(request, data=data)
print(response.read().decode('utf8'))
# 登录成功之后,向这个url发送请求
get_url = 'url2'
request1 = urllib.request.Request(url=get_url, headers=headers)
r = opener.open(request1)
with open('renren.html', 'wb') as fp:
fp.write(r.read())
urllib-cookie
最新推荐文章于 2024-03-13 14:10:26 发布