您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

python使用cookielib库示例分享

2024/12/11 7:49:18发布17次查看
该模块主要功能是提供可存储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实例。
代码:
复制代码 代码如下:
 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()
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product