Cookie

作者: 低吟浅唱1990 | 来源:发表于2017-05-16 22:34 被阅读10次

转自http://blog.csdn.net/seanliu96/article/details/60317333
<pre>
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))
</pre>

把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).
<pre>
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内容

</pre>

相关文章

网友评论

      本文标题:Cookie

      本文链接:https://www.haomeiwen.com/subject/hohrxxtx.html