FileCookieJar的子类MozillaCookieJar和LWPCookieJar实现了save()方法。
# 经典实例1:
import http.cookiejar,urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True,ignore_expires=True)
# save()函数带有两个参数,ignore_discard和ignore_expires。
#
# ignore_discard: 即保存需要被丢弃的cookie。
# ignore_expires: 即过期的cookie也保存。
# # 经典实例二:
# import http.cookiejar,urllib.request
# cookie = http.cookiejar.MozillaCookieJar()
# handler = urllib.request.HTTPCookieProcessor(cookie)
# opener = urllib.request.build_opener(handler)
# request = urllib.request.Request('http://www.baidu.com')
# #用Request类构建了一个完整的请求,增加了headers等一些信息
# urllib.request.urlopen(request)
# cookie.save('cookie1.txt')
# # 将cookie存为一个文件
# cookie1 = http.cookiejar.MozillaCookieJar()
# cookie1.load('cookie1.txt')
# # 从文件中读取cookie
# for i in cookie1:
# print(i.name+"="+i.vaule)
# 经典案例3
import http.cookiejar,urllib.request
cookie = http.cookiejar.LWPCookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))