wangluo010 发表于 2015-4-24 05:35:10

Python中Cookie的处理(二)cookielib库

  Python中cookielib库(python3中为http.cookiejar)为存储和管理cookie提供客户端支持。
  该模块主要功能是提供可存储cookie的对象。使用此模块捕获cookie并在后续连接请求时重新发送,还可以用来处理包含cookie数据的文件。
  这个模块主要提供了这几个对象,CookieJar,FileCookieJar,MozillaCookieJar,LWPCookieJar。
  1. CookieJar
  CookieJar对象存储在内存中。



>>> import urllib2
>>> import cookielib
>>> cookie=cookielib.CookieJar()
>>> handler=urllib2.HTTPCookieProcessor(cookie)
>>> opener=urllib2.build_opener(handler)
>>> opener.open('http://www.google.com.hk')
  访问google的cookie已经被捕捉了,来看下是怎样的:



>>> print cookie

  看来是Cookie实例的集合,Cookie实例有name,value,path,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. 将cookie捕捉到文件
  FileCookieJar(filename)
  创建FileCookieJar实例,检索cookie信息并将信息存储到文件中,filename是文件名。
  MozillaCookieJar(filename)
  创建与Mozilla cookies.txt文件兼容的FileCookieJar实例。
  LWPCookieJar(filename)
  创建与libwww-perl Set-Cookie3文件兼容的FileCookieJar实例。
  代码:



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()
19   print MozillaCookieJarFile      
20   MozillaCookieJarFile.load(readfilename)
21   print MozillaCookieJarFile
22 if __name__=="__main__":
23   HandleCookie()

  
  
页: [1]
查看完整版本: Python中Cookie的处理(二)cookielib库