Python中cookielib庫(python3中為http.cookiejar)為存儲和管理cookie提供客戶端支持。
該模塊主要功能是提供可存儲cookie的對象。使用此模塊捕獲cookie並在后續連接請求時重新發送,還可以用來處理包含cookie數據的文件。
這個模塊主要提供了這幾個對象,CookieJar,FileCookieJar,MozillaCookieJar,LWPCookieJar。
1. CookieJar
CookieJar對象存儲在內存中。
>>> import urllib2 >>> import cookielib >>> cookie=cookielib.CookieJar() >>> handler=urllib2.HTTPCookieProcessor(cookie) >>> opener=urllib2.build_opener(handler) >>> opener.open('http://www.google.com.hk')
訪問google的cookie已經被捕捉了,來看下是怎樣的:
>>> 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/>]>
看來是Cookie實例的集合,Cookie實例有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)
創建FileCookieJar實例,檢索cookie信息並將信息存儲到文件中,filename是文件名。
MozillaCookieJar(filename)
創建與Mozilla cookies.txt文件兼容的FileCookieJar實例。
LWPCookieJar(filename)
創建與libwww-perl Set-Cookie3文件兼容的FileCookieJar實例。
代碼:
2 import urllib2 3 import cookielib 4 def HandleCookie(): 5 6 #handle cookie whit file 7 filename='FileCookieJar.txt' 8 url='http://www.google.com.hk' 9 FileCookieJar=cookielib.LWPCookieJar(filename) 10 FileCookeJar.save() 11 opener =urllib2.build_opener(urllib2.HTTPCookieProcessor(FileCookieJar)) 12 opener.open(url) 13 FileCookieJar.save() 14 print open(filename).read() 15 16 #read cookie from file 17 readfilename = "readFileCookieJar.txt" 18 MozillaCookieJarFile =cookielib.MozillaCookieJar() 19 print MozillaCookieJarFile 20 MozillaCookieJarFile.load(readfilename) 21 print MozillaCookieJarFile 22 if __name__=="__main__": 23 HandleCookie()