urllib2模块、cookielib模块
urllib2模块
urllib模块和urllib模块类似,用来打开URL并从中获取数据。与urllib模块不同的是,urllib模块不仅可以使用urlopen() 函数还可以自定义Opener来访问网页。同时要注意:urlretrieve()函数是urllib模块中的,urllib2模块中不存在该函数。但是 使用urllib2模块时一般都离不开urllib模块,因为POST的数据需要使用urllib.urlencode()函数来编码。
一、urlopen()
最简单的请求方式就是用urlopen()函数。
urlopen (url [,data ,[timeout]]) 函数打开URL url并返回类文件对象,使用该对象可以读取返回的内容。其中,参数url 可以是包含URL的字符串,也可以是urllib2.Request类的实例。data是经过编码的POST数据(一般使用 urllib.urlencode()来编码)。timeout是可选的超时期(以秒为单位),供所有阻塞操作内部使用。
注意timeout参数,是超时时间,即在中断连接前尝试的时间,但只对HTTP、HTTPS、FTP、FTPS有效。设置超时时间,通过 urlopen()函数设置是最简单的方法,还可以通过socket模块或urllib2模块来设置 (socket.setdefaulttimeout(10)或urllib2.socket.setdefaulttimeout(10))。详细代码 参考《urllib2的使用细节》.
urlopen()返回的类文件对象u支持一下方法:

对于简单的请求,urlopen()的参数url就是一个代表URL的字符串。但如果需要执行更复杂的操作,如修改HTTP报头,可以创建Request实例并将其作为url参数。
Request (url [data,headers [,origin_req_host ,[unverifiable]]]])

Request实例r具有的方法中重要的有以下几个:


下面代码示例使用Request来更改urlopen()使用的User-Agent报头的方法:
headers={"User-Agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
rq=urllib2.Request("http://www.example.com",headers=headers)
u=urlopen(rg)
二、自定义Opener
基本的urlopen()函数不支持验证、cookie或其他HTTP高级功能。要支持这些功能,必须使用build_opener()函数来创建自己的自定义Opener对象。

install_opener(opener) 安装opener作为urlopen()使用的全局URL opener,即意味着以后调用urlopen()时都会使用安装的opener对象。opener通常是build_opener()创建的 opener对象。
复杂情况详细解决办法:
1、cookie处理
如果要管理HTTP cookie,需要创建添加了HTTPCookieProcessor处理程序的opener对象。默认情况下。HTTPCookieProcessor 使用CookieJar对象,将不同类型的CookieJar对象作为HTTPCookieProcessor的参数提供,可支持不同的cookie处 理。如下面代码:
mcj=cookielib.MozillaCookieJar("cookies.txt")
cookiehand=HTTPCookieProcessor(mcj)
opener=urllib2.build_opener(cookiehand)
u=opener.open(http://www.baidu.com)
2、密码验证
3、代理
urllib2会自动检测代理设置,默认使用环境变量http_proxy 来设置 HTTP Proxy通常情况下,这是很有帮助的,因为也可能造成麻烦(因为通过代理获取本地URL资源时会被阻止,因此如果你正在通过代理访问Internet, 那么使用脚本测试本地服务器时必须阻止urllib2模块使用代理)。因此,如果想在程序中明确Proxy的使用而不受环境变量的影响,可以通过创建 ProxyHandler实例,并将实例作为build_opener()的参数来实现。如下面代码:
import urllib2 enable_proxy = True
proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})
null_proxy_handler = urllib2.ProxyHandler({}) if enable_proxy:
opener = urllib2.build_opener(proxy_handler)
else:
opener = urllib2.build_opener(null_proxy_handler) urllib2.install_opener(opener)
cookielib模块
cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源。例如可以利用本模块 的CookieJar类的对象来捕获cookie并在后续连接请求时重新发送。coiokielib模块用到的对象主要有下面几个:CookieJar、 FileCookieJar、MozillaCookieJar、LWPCookieJar。其中他们的关系如下:
CookieJar
/
FileCookieJar
/ \
MozillaCookieJar LWPCookieJar
1、CookieJar ()
管理HTTP cookie值、存储HTTP请求生成的cookie、向传出的HTTP请求添加cookie的对象。整个cookie都存储在内存中,对CookieJar实例进行垃圾回收后cookie也将丢失。
The CookieJar class stores HTTP cookies. It extracts cookies from HTTP requests, and returns them in HTTP responses.CookieJar instances automatically expire contained cookies when necessary. Subclasses are also responsible for storing and retrieving cookies from a file or database.
2、FileCookieJar (filename,delayload=None,policy=None)
创建FileCookieJar实例,检索cookie信息并将cookie存储到文件中。filename是存储cookie的文件名。delayload为True时支持延迟访问访问文件,即只有在需要时才读取文件或在文件中存储数据。
A CookieJar which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are NOT loaded from the named file until either the load() or revert() method is called.
3、MozillaCookieJar (filename,delayload=None,policy=None)
创建与Mozilla浏览器cookies.txt兼容的FileCookieJar实例。
A FileCookieJar that can load from and save cookies to disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers).Also note that cookies saved while Mozilla is running will get clobbered by Mozilla.
4、LWPCookieJar (filename,delayload=None,policy=None)
创建与libwww-perl的Set-Cookie3文件格式兼容的FileCookieJar实例。
A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3file format. This is convenient if you want to store cookies in a human-readable file.
除了上面几个函数之外,下面几个函数也很重要:
- 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 expiredThe 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.
- FileCookieJar. load ( filename=None , ignore_discard=False , ignore_expires=False )
-
Load cookies from a file.Old cookies are kept unless overwritten by newly loaded ones.Arguments are as for save().The named file must be in the format understood by the class, or LoadError will be raised. Also, IOError may be raised, for example if the file does not exist.
- FileCookieJar. revert ( filename=None , ignore_discard=False , ignore_expires=False )
-
Clear all cookies and reload cookies from a saved file. revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered.
cookielib模块一般与urllib2模块配合使用,主要用在urllib2.build_oper()函数中作为urllib2.HTTPCookieProcessor()的参数。使用方法如下面登录人人网的代码:
#! /usr/bin/env python
#coding=utf-8
import urllib2
import urllib
import cookielib
data={"email":"用户名","password":"密码"} #登陆用户名和密码
post_data=urllib.urlencode(data)
cj=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
req=urllib2.Request("http://www.renren.com/PLogin.do",post_data,headers)
content=opener.open(req)
print content2.read().decode("utf-8").encode("gbk")
urllib2模块、cookielib模块的更多相关文章
- 【转】cookielib模块
cookielib模块 cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源.例如可以利用本模块 的CookieJar类的对象来 ...
- python—cookielib模块对cookies的操作
最近用python写爬虫爬了点数据,确实是很好用的东西,今天对python如何操作cookie进行一下总结. python内置有cookielib模块操作cookie,配合urllib模块就可以了很轻 ...
- cookielib模块基础学习
# -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' import cookielib #主要用于处理http客户端的co ...
- Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块
Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 ...
- cookielib模块 for python3
python2 可以直接安装cookielib模块 而py3却不能安装 故需要安装http模块 举例子: from http import cookiejar cookie = cookiejar.C ...
- Python3使用cookielib模块
同时使用过python2和python3的应该都知道,好多模块在python2中能直接安装,但是到了python3中却无法安装直接使用,同样python3中的好些模块在python2中也是一样 如下: ...
- Python cookielib 模块
什么是 cookie : 指某些网站为了辨别用户身份,进行 session 跟踪而储存在用户本地终端上的数据,通常以 txt 文件形式存储.比如你登录了淘宝,浏览器就会保存 cookie 信息,这样我 ...
- python urllib、urlparse、urllib2、cookielib
1.urllib模块 1.urllib.urlopen(url[,data[,proxies]]) 打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作.本例试着打开google i ...
- Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块
Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fab ...
随机推荐
- String作为输出型参数时获取不到值
有时候在一个方法中,我们需要返回多个字符串,而又不想将这些字段包成一个类.此时就需要使用输出型参数. 但是如果将输出型参数的类型声明为String,那么调用该方法后,是获取不到我们想要的值的. 测试代 ...
- uploadify图片上传配置
参考:http://www.cnblogs.com/XuebinDing/archive/2012/04/26/2470995.html 官网地址:http://www.uploadify.com/ ...
- java collection(一)
1.Collection层次结构: 2.集合Conllection的基本概念: (1)集合的基本认识:如StringBuffer&StringBuilder是集合(存储的对象类型是String ...
- Tomcat报错:Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JFreeChartTest]]
最好把项目移除,然后在tomcat的webapps发布路径下也把项目文件删掉,重新部署就好了,原因是可能在tomcat的remove覆盖中以前的文件有所保留导致冲突,亲测有效
- u3d局域网游戏网络(c# socket select 模型)
之前写了一篇. 发完之后第二天实际应用到游戏之后还是发现了一些小毛病. 比如网络模块有重复使用(多对象)的情况.所以将静态类该成了普通类. 比如安卓下会有些异常出现导致游戏逻辑不正常.所以网络相关的函 ...
- 【bzoj2038-小z的袜子】莫队算法
莫队例题. 莫队学习:https://www.cnblogs.com/Paul-Guderian/p/6933799.html 本题 分子是sigma(c(sum[a[i]],2)),分母是sigma ...
- UIImageView与UIScrollView的关系图
UIImageView与UIScrollView的关系图 https://www.evernote.com/shard/s227/sh/0af9f23c-08e6-4be6 ...
- 【洛谷 T47488】 D:希望 (点分治)
题目链接 看到这种找树链的题目肯定是想到点分治的. 我码了一下午,\(debug\)一晚上,终于做到只有两个点TLE了. 我的是不完美做法 加上特判\(A\)了这题qwq 记录每个字母在母串中出现的所 ...
- hdu 1102 Constructing Roads (最小生成树)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1102 Constructing Roads Time Limit: 2000/1000 MS (Jav ...
- python中的ftplib模块
前言 Python中默认安装的ftplib模块定义了FTP类. ftplib模块相关参数: 加载ftp模块:from ftplib import FTP ftp = FTP()#设置变量ftp.set ...