默认的是FileCookieJar没有实现save函数。
而MozillaCookieJar或LWPCookieJar都已经实现了。
所以可以用MozillaCookieJar或LWPCookieJar,去自动实现cookie的save。
实现,通过文件保存cookie。
建议用LWPCookieJar,其保存的cookie,易于人类阅读
【问题】
用python代码:
import cookielib;
gVal['cj'] = cookielib.FileCookieJar(localCookieFileName);
#create cookie file
gVal['cj'].save();
结果出错:
crifanLib.initAutoHandleCookies("localCookieFile.txt"); gVal['cj'].save(); File "D:\tmp\dev_install_root\Python27_x64\lib\cookielib.py", line 1753, in save raise NotImplementedError() NotImplementedError |
【解决过程】
1.之前已经大概看了,python的手册的解释了:
FileCookieJar. save ( filename=None , ignore_discard=False , ignore_expires=False )
Save cookies to a file.
This base class raises NotImplementedError . Subclasses may leave this method unimplemented.
filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None , ValueError is raised.
ignore_discard : save even cookies set to be discarded. ignore_expires : save even cookies that have expired
The file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods.
但是不太懂。
2.参考:
Python FileCookieJar.save() issue
得知,可以改用MozillaCookieJar或LWPCookieJar。
3.所以去试了试:
针对
- 使用LWPCookieJar的代码:
import cookielib;
gVal['cj'] = cookielib.LWPCookieJar(localCookieFileName);
#create cookie file
gVal['cj'].save();
- 得到cookie结果是:
#LWP-Cookies-2.0
Set-Cookie3: PREF="ID=4d37691401c67131:FF=0:NW=1:TM=1358232482:LM=1358232482:S=uJuXpzeOCHiPXC6n"; path="/"; domain=".google.com"; path_spec; domain_dot; expires="2015-01-15 06:48:02Z"; version=0Set-Cookie3: NID="67=kHDkitb44zdLIFhq_X20E17jh0wOpAId1yiPja9butDIsD1Cefs2YaqSZPYuVEysTpcRCoOSKBtCLzMDqHJRXHgtlymYIBW7XvztYXrtDEdTfhj_Q4vsWOT9bms69bGv"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2013-07-17 06:48:02Z"; HttpOnly=None; version=0
Set-Cookie3: PREF="ID=c6950eb3132a355d:U=64ec79359ad60919:FF=2:LD=zh-CN:NW=1:TM=1358232482:LM=1358232482:S=WvKpG_uygzjmn_Lr"; path="/"; domain=".google.com.hk"; path_spec; domain_dot; expires="2015-01-15 06:48:02Z"; version=0
- 得到cookie结果是:
- 对应官网解释是:
A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3 file format. This is convenient if you want to store cookies in a human-readable file.
- 对应官网解释是:
- 使用MozillaCookieJar的代码是:
import cookielib; gVal['cj'] = cookielib.MozillaCookieJar(localCookieFileName); #create cookie file gVal['cj'].save();
- 得到cookie结果是:
# Netscape HTTP Cookie File
# http://www.netscape.com/newsref/std/cookie_spec.html# This is a generated file! Do not edit.
.google.com TRUE / FALSE 1421304599 PREF ID=e33b271ab0f40036:FF=0:NW=1:TM=1358232599:LM=1358232599:S=6bX8PSZAJwtaGpi1
.google.com.hk TRUE / FALSE 1374043799 NID 67=SQ5oTYjveXizHv3GNMOJx1gv0E87mTEAXlAHuqievzqo5CdD2yxmguzEErBcSJKUEG8pPege-JkD4PyiPGHltVF9bgTpjIvZc24nVZI9G5Fk1SRpSqsLk6DxDl-i4yj7.google.com.hk TRUE / FALSE 1421304599 PREF ID=9de55a3cd7314a09:U=c2e0eee9da3b56c4:FF=2:LD=zh-CN:NW=1:TM=1358232599:LM=1358232599:S=PclH1oPP1AIXo0Yl
【总结】
默认的是FileCookieJar没有实现save函数。
而MozillaCookieJar或LWPCookieJar都已经实现了。
所以可以用MozillaCookieJar或LWPCookieJar,去自动实现cookie的save。
实现,通过文件保存cookie。
建议用LWPCookieJar,其保存的cookie,易于人类阅读。
=========================================
四、从HTML文档中提取Cookies
很多时候,我们都需要处理Cookie,幸运的是Python语言的cookielib模块为我们提供了许多自动处理在HTML中的HTTP Cookie的类。当处理要求为客户端设置Cookie的HTML文档的时候,这些类对我们非常有用。
import cookielib
from urllib2 import urlopen, Request
cJar = cookielib.LWPCookieJar()
opener = urllib2.build_opener( \
urllib2.HTTPCookieProcessor(cJar))
urllib2.install_opener(opener)
r = Request(testURL)
h = urlopen(r)
for ind, cookie in enumerate(cJar):
print " %d - %s " % (ind, cookie)
cJar.save(cookieFile)
为了从HTML文档提取cookies,首先得使用cookielib模块的LWPCookieJar()函数创建一个cookie jar的实例。LWPCookieJar()函数将返回一个对象,该对象可以从硬盘加载Cookie,同时还能向硬盘存放Cookie。
接下来,使用urllib2模块的build_opener([handler, . . .])函数创建一个opener对象,当HTML文件打开时该对象将处理cookies。函数build_opener可以接收零个或多个处理程序(这些程序将按照它们被指定的顺序连接在一起)作为参数并返回一个。
注意,如果想让urlopen()使用opener对象来打开HTML文件的话,可以调用install_opener(opener)函数,并将opener对象传给它。否则,请使用opener对象的open(url)函数来打开HTML文件。
一旦已经创建并安装了opener对象,就可以使用urllib2模块中的Request(url)函数来创建一个Request对象,然后就能使用urlopen(Request)函数来打开HTML文件了。
打开HTML页面后,该页面的所有Cookie将被存放到LWPCookieJar对象中,之后,您可以使用LWPCookieJar对象的save(filename)函数了。
import urllib2
import cookielib
from urllib2 import urlopen, Request
cookieFile = " cookies.dat "
testURL = ' http://maps.google.com/ '
# 为cookie jar 创建实例
cJar = cookielib.LWPCookieJar()
# 创建HTTPCookieProcessor的opener对象
opener = urllib2.build_opener( \
urllib2.HTTPCookieProcessor(cJar))
# 安装HTTPCookieProcessor的opener
urllib2.install_opener(opener)
# 创建一个Request对象
r = Request(testURL)
# 打开HTML文件
h = urlopen(r)
print " 页面的头部\n====================== "
print h.info()
print " 页面的Cookies\n====================== "
for ind, cookie in enumerate(cJar):
print " %d - %s " % (ind, cookie)
# 保存cookies
cJar.save(cookieFile)
上述代码的运行结果如下所示:
======================
Cache - Control: private
Content - Type: text / html; charset = ISO - 8859 - 1
Set - Cookie: PREF = ID = 5d9692b55f029733:NW = 1 :TM = 1246015608 :LM = 1246015608 :S = frfx -- b3xt73TaEA; expires = Sun, 26 - Jun - 2011 11 : 26 : 48 GMT; path =/ ; domain = .google.com
Date: Fri, 26 Jun 2009 11 : 26 : 48 GMT
Server: mfe
Expires: Fri, 26 Jun 2009 11 : 26 : 48 GMT
Transfer - Encoding: chunked
Connection: close
页面的Cookies
======================
0 -