該模塊主要功能是提供可存儲(chǔ)cookie的對(duì)象。使用此模塊捕獲cookie并在后續(xù)連接請(qǐng)求時(shí)重新發(fā)送,還可以用來(lái)處理包含cookie數(shù)據(jù)的文件。
這個(gè)模塊主要提供了這幾個(gè)對(duì)象,CookieJar,F(xiàn)ileCookieJar,MozillaCookieJar,LWPCookieJar。
1. CookieJar
CookieJar對(duì)象存儲(chǔ)在內(nèi)存中。
>>> import urllib2
>>> import cookielib
>>> cookie=cookielib.CookieJar()
>>> handler=urllib2.HTTPCookieProcessor(cookie)
>>> opener=urllib2.build_opener(handler)
>>> opener.open('http://www.google.com.hk')
訪(fǎng)問(wèn)google的cookie已經(jīng)被捕捉了,來(lái)看下是怎樣的:
>>> print cookie
<cookielib.CookieJar[<Cookie NID=67=B6YQoEIEjcqDj-adada_WmNYl_JvADsDEDchFTMtAgERTgRjK452ko6gr9G0Q5p9h1vlmHpCR56XCrWwg1pv6iqhZnaVlnwoeM-Ln7kIUWi92l-X2fvUqgwDnN3qowDW for .google.com.hk/>, <Cookie PREF=ID=7ae0fa51234ce2b1:FF=0:NW=1:TM=1391219446:LM=1391219446:S=cFiZ5X8ts9NY3cmk for .google.com.hk/>]>
看來(lái)是Cookie實(shí)例的集合,Cookie實(shí)例有name,value,path,expires等屬性:
>>> for ck in cookie:
... print ck.name,':',ck.value
...
NID : 67=B6YQoEIEjcqDj-adada_WmNYl_JvADsDEDchFTMtAgERTgRjK452ko6gr9G0Q5p9h1vlmHpCR56XCrWwg1pv6iqhZnaVlnwoeM-Ln7kIUWi92l-X2fvUqgwDnN3qowDW
PREF : ID=7ae0fa51234ce2b1:FF=0:NW=1:TM=1391219446:LM=1391219446:S=cFiZ5X8ts9NY3cmk
2.將cookie捕捉到文件
FileCookieJar(filename)
創(chuàng)建FileCookieJar實(shí)例,檢索cookie信息并將信息存儲(chǔ)到文件中,filename是文件名。
MozillaCookieJar(filename)
創(chuàng)建與Mozilla cookies.txt文件兼容的FileCookieJar實(shí)例。
LWPCookieJar(filename)
創(chuàng)建與libwww-perl Set-Cookie3文件兼容的FileCookieJar實(shí)例。
代碼:
import urllib2
import cookielib
def HandleCookie():
#handle cookie whit file
filename='FileCookieJar.txt'
url='http://www.google.com.hk'
FileCookieJar=cookielib.LWPCookieJar(filename)
FileCookeJar.save()
opener =urllib2.build_opener(urllib2.HTTPCookieProcessor(FileCookieJar))
opener.open(url)
FileCookieJar.save()
print open(filename).read()
#read cookie from file
readfilename = "readFileCookieJar.txt"
MozillaCookieJarFile =cookielib.MozillaCookieJar(readfilename)
print MozillaCookieJarFile
MozillaCookieJarFile.load(cookieFilenameMozilla)
print MozillaCookieJarFile
if __name__=="__main__":
HandleCookie()