Cookie

转自http://blog.csdn.net/seanliu96/article/details/60317333


import urllib.request
import http.cookiejar
url = 'http://www.baidu.com'

声明一个CookieJar对象

cookie = http.cookiejar.CookieJar()

利用urllib库的HTTPCookieProcessor对象来创建cookie处理器

handler = urllib.request.HTTPCookieProcessor(cookie)

通过handler来构件opener

opener = urllib.request.build_opener(handler)

此处的opener方法同urllib的urlopen方法, 也可以先install_opener

response = opener.open(url)
for item in cookie:
print('name:%s \nvalue:%s'%(item.name,item.value))

把cookie内容写入文件
http.cookiejar.MozillaCookieJar(filename, delayload=None, policy=None)
A FileCookieJar that can load from and save cookies to
disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers).


import urllib.request
import http.cookiejar
url = 'http://www.baidu.com'
filename = 'cookies.txt'
mozilla_cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(mozilla_cookie)
opener = urllib.request.build_opener(handler)
request = urllib.request.Request(url)
reponse = opener.open(request)
print(reponse.read())
mozilla_cookie.save(ignore_discard = True,ignore_expires = True)

mozilla_cookie.load(filename,ignore_discard=True,ignore_expires=True) 从文件中载入 cookie内容

你可能感兴趣的:(Cookie)