Python中Cookie的處理(二)cookielib庫

來源:互聯網
上載者:User
Python中cookielib庫(python3中為http.cookiejar)為儲存和管理cookie提供用戶端支援。

該模組主要功能是提供可儲存cookie的對象。使用此模組捕獲cookie並在後續串連請求時重新發送,還可以用來處理包含cookie資料的檔案。

這個模組主要提供了這幾個對象,CookieJar,FileCookieJar,MozillaCookieJar,LWPCookieJar。

1. CookieJar

CookieJarObject Storage Service在記憶體中。

>>> 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()

以上就是Python中Cookie的處理(二)cookielib庫的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.