- 所需库:urllib.request和http.cookiejar
import urllib.request
import http.cookiejar
- 步骤:
- 声明一个cookieJar对象
cookie = http.cookiejar.cookieJar()
cookie = http.cookiejar.MozillacookieJar(cookie.txt)
#MozillacookieJar(cookie.txt)可将cookie保存
2.用HTTPCookieProcessor(cookie)处理器构建一个handler
handler = urllib.request.HTTPCookieProcessor(cookie)
3.用build_opener(handler)构建一个opener
opener = urllib.request.build_opener(handler)
4.用opener.open(url)打开
r = opener.open(url)
5.用cookie.save()保存获取的cookie
cookie.save(ignore_discard = True, ignore_expires = True)
#ignore_discard(丢弃)ignore_expires(文件协议失效)
- 完整代码
#cookies获取与保存
import urllib.request
import http.cookiejar
url = 'http://www.baidu.com'
filename = "cookie.txt"
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
r = opener.open(url)
print(type(cookie))
for c in cookie:
print(c.name + '=' + c.value)
cookie.save(ignore_discard=True, ignore_expires=True)