In Python, the cookielib Library (http. cookiejar in python3) provides client support for storing and managing cookies. The following is an example. 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.
The 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:
The code is as follows:
>>> Print cookie
, ]>
It seems to be a set of Cookie instances. Cookie instances have attributes such as name, value, path, and expires:
The 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:
The 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 ()