In Python, the cookielib Library (http. cookiejar in python3) provides clients for the storage and management of cookies. in Python, the cookielib Library (http. cookiejar in python3) provides client support for the storage and management of 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
, ]>
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-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:
2 import urllib2
3 import cookielib
4 def HandleCookie ():
5
6 # handle cookie whit file
7 filenamepolic'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 export illacookiejarfile = cookielib. unzip illacookiejar ()
19 print export illacookiejarfile
20 MozillaCookieJarFile. load (readfilename)
21 print export illacookiejarfile
22 if _ name __= = "_ main __":
23 HandleCookie ()
The above is the content of the cookielib library for processing cookies in Python (2). For more information, see PHP Chinese website (www.php1.cn )!