您的位置:首页 > 编程语言 > Python开发

python学习笔记 --- 关于cookielib

2016-08-22 18:19 295 查看
有些网站在cookies未启用时不能被浏览。他们被用来存储会话信息或确认用户的身份。有时他们也被用来作为一种替代方案,就像basic authentication。

urllib2默认情况下不处理cookies。在python2.4之前,存在一个库ClientCookie,但是之后的版本一些功能已经并入urllib2.现在主要使用的是cookielib。

无论是cookielib还是ClientCookie,都将cookies保存在一个文件上。服务器会返回URLs,但是任何cookies不会被处理和保存。

cookies

当网站发送页面到客户端时,它会先传送一组headers来描述HTTP事物,送回来的headers中包含的一些文本就是cookies。如果想要从相同服务器返回其他页面,那么这些cookies就必须作为请求的headers传送给服务器。这就意味着cookies会储存一些信息让服务器来识别你。

下面来看看如何先导入cookielib,然后是ClientCookie,如果这两个都不能用,就默认导入urllib2:

<span style="font-size:14px;">import os.path
import urllib2

COOKIEFILE = 'cookies.lwp'
# the path and filename to save your cookies in

cj = None
ClientCookie = None
cookielib = None

# Let's see if cookielib is available
try:
import cookielib
except ImportError:
# If importing cookielib fails
# let's try ClientCookie
try:
import ClientCookie
except ImportError:
# ClientCookie isn't available either
urlopen = urllib2.urlopen
Request = urllib2.Request
else:
# imported ClientCookie
urlopen = ClientCookie.urlopen
Request = ClientCookie.Request
cj = ClientCookie.LWPCookieJar()

else:
# importing cookielib worked
urlopen = urllib2.urlopen
Request = urllib2.Request
cj = cookielib.LWPCookieJar()
# This is a subclass of FileCookieJar
# that has useful load and save methods</span>

如果已经成功地导入一个cookie处理库,那么接下来就要将名字为cj的绑定到CookieJar的实例去。

我们需要将CookieJar安装在默认的opener去返回URLs。这就意味着所有调用urlopen都有处理cookies的功能。而实际操作是由HTTPCookieProcessor对象来完成的。

下面这些都是在ClientCookie或是urllib2中完成的,主要取决于成功导入的模块:

<span style="font-size:14px;">if cj is not None:
# we successfully imported
# one of the two cookie handling modules

if os.path.isfile(COOKIEFILE):
# if we have a cookie file already saved
# then load the cookies into the Cookie Jar
cj.load(COOKIEFILE)

# Now we need to get our Cookie Jar
# installed in the opener;
# for fetching URLs
if cookielib is not None:
# if we use cookielib
# then we get the HTTPCookieProcessor
# and install the opener in urllib2
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

else:
# if we use ClientCookie
# then we get the HTTPCookieProcessor
# and install the opener in ClientCookie
opener = ClientCookie.build_opener(ClientCookie.HTTPCookieProcessor(cj))
ClientCookie.install_opener(opener)</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: