In PythonCookielibLibrary (http. cookiejar in python3) provides client support for storing and managing cookies.
The main function of this module is to provide objects that can store cookies. This module captures cookies and resends them in subsequent connection requests. It can also be used to process files containing cookie data.
This module provides the following objects: CookieJar, FileCookieJar, MozillaCookieJar, and LWPCookieJar.
1. CookieJar
CookieJar objects are stored in the memory.
>>> import urllib2>>> import cookielib>>> cookie=cookielib.CookieJar()>>> handler=urllib2.HTTPCookieProcessor(cookie)>>> opener=urllib2.build_opener(handler)>>> opener.open('http://www.google.com.hk')
The cookie used to access google has been captured. Let's take a look at the following:
>>> 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/>]>
It seems to be a set of Cookie instances. Cookie instances have attributes such as name, value, path, and expires:
>>> for ck in cookie:... print ck.name,':',ck.value... NID : 67=B6YQoEIEjcqDj-adada_WmNYl_JvADsDEDchFTMtAgERTgRjK452ko6gr9G0Q5p9h1vlmHpCR56XCrWwg1pv6iqhZnaVlnwoeM-Ln7kIUWi92l-X2fvUqgwDnN3qowDWPREF : ID=7ae0fa51234ce2b1:FF=0:NW=1:TM=1391219446:LM=1391219446:S=cFiZ5X8ts9NY3cmk
2. Capture cookies to files
FileCookieJar(Filename)
Create a FileCookieJar instance, retrieve the cookie information, and store the information in the file. filename is the file name.
MozillaCookieJar(Filename)
Create a FileCookieJar instance compatible with the Mozilla cookies.txt file.
LWPCookieJar(Filename)
Create a FileCookieJar instance that is compatible with libwww-perl Set-Cookie3 files.
Code:
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(readfilename) 19 print MozillaCookieJarFile 20 MozillaCookieJarFile.load(cookieFilenameMozilla) 21 print MozillaCookieJarFile 22 if __name__=="__main__": 23 HandleCookie()