Python USES the cookielib library for example sharing

  • 2020-04-02 13:28:54
  • OfStack

The main function of this module is to provide objects that can store cookies. Use this module to capture cookies and resend them on subsequent connection requests, and to work with files that contain cookie data.

This module provides a few main object, CookieJar, FileCookieJar, MozillaCookieJar, LWPCookieJar.

1. CookieJar

The CookieJar object is stored in 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 accessing Google has been caught. Here's what it looks like:


>>> 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 collection of Cookie instances. Cookie instances have properties such as name,value,path,expires, etc.


>>> 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 the cookie to a file

FileCookieJar (filename)

Create a FileCookieJar instance, retrieve the cookie information, and store the information in a file, filename being the name of the file.

MozillaCookieJar (filename)

Create a FileCookieJar instance that is compatible with the Mozilla cookies. TXT file.

LWPCookieJar (filename)

Create a FileCookieJar instance that is compatible with the libww-perl set-cookie3 file.

Code:


 import urllib2
import cookielib
def HandleCookie():
#handle cookie whit file
     filename='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"
     MozillaCookieJarFile =cookielib.MozillaCookieJar(readfilename)
     print MozillaCookieJarFile        
     MozillaCookieJarFile.load(cookieFilenameMozilla)
     print MozillaCookieJarFile
 if __name__=="__main__":
     HandleCookie()


Related articles: