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.
Copy codeThe Code is as follows:
>>> 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:
Copy codeThe Code is as follows:
>>> 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:
Copy codeThe Code is as follows:
>>> 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. 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:
Copy codeThe Code is as follows:
Import urllib2
Import cookielib
Def HandleCookie ():
# Handle cookie whit file
Filenamepolic'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"
Using illacookiejarfile = cookielib. Using illacookiejar (readfilename)
Print export illacookiejarfile
MozillaCookieJarFile. load (cookieFilenameMozilla)
Print export illacookiejarfile
If _ name __= = "_ main __":
HandleCookie ()