Save cookies locally
To save cookies locally, you can use the save method of cookiejar and need to specify a file name:
from urllib import request
from http.cookiejar import MozillaCookieJar
#保存到电脑的cookie.txt位置
cookiejar = MozillaCookieJar("cookie.txt")
handler = request.HTTPCookieProcessor(cookiejar)
opener = request.build_opener(handler)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
req = request.Request('http://httpbin.org/cookies',headers=headers)
resp = opener.open(req)
print(resp.read())
#ignore_discard保存即将过期的cookie信息
cookiejar.save(ignore_discard=True,ignore_expires=True)
Save cookie information for Baidu pages
from urllib import request
from http.cookiejar import MozillaCookieJar
cookiejar = MozillaCookieJar("cookie.txt")
handler = request.HTTPCookieProcessor(cookiejar)
opener = request.build_opener(handler)
resp=opener.open("http://www.baidu.com/")
cookiejar.save(ignore_discard=True)
Cookie expiration means that the cookie information will expire when the page is closed. Use ignore_discard=True to save the cookie information that is about to expire.
Load cookies from local:
To load cookies locally, you need to use the load method of cookiejar, and you also need to specify the method:
from urllib import request
from http.cookiejar import MozillaCookieJar
cookiejar = MozillaCookieJar("cookie.txt")
#加载即将过期的cookie信息
cookiejar.load(ignore_expires=True,ignore_discard=True)
handler = request.HTTPCookieProcessor(cookiejar)
opener = request.build_opener(handler)
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
}
req = request.Request('http://httpbin.org/cookies',headers=headers)
resp = opener.open(req)
print(resp.read())
The full text is video study notes