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 ...
随机推荐
- Http字段含义
转载自:http://blog.csdn.net/sand_ant/article/details/10503579 一.request请求Header简介 Accept:--客户机支持的类型 Acc ...
- II8部署WCF服务出错
环境:Windows 2012 R2 + IIS 8.0 + .NET 4.5 错误404.3 - Not Found: 控制面板->程序->启用或关闭Windows功能,如下图所示,将需 ...
- Scala环境安装设置
Scala语言可以安装在任何类UNIX或Windows系统.要安装Scala,必须先安装Java1.5或更高版本安装在计算机上. Windows上安装Scala: 步骤(1):JAVA设置: 首先,必 ...
- free命令buff和cache的区别
[root@iz8vb8kca7twx6177bqg0fz ~]# free -h total used free shared b ...
- 如果你也想写个完整的 Vue 组件项目
1.一个完整的组件项目需要什么? 必要的: 组件构建方式 ( webpack / rollup 之类 ),并提供至少一个主流的输出格式 (ESModule) Demo 及 Demo 源码 文档,可以是 ...
- Spring boot 集成Dubbox(山东数漫江湖)
前言 因为工作原因,需要在项目中集成dubbo,所以去查询dubbo相关文档,发现dubbo目前已经不更新了,所以把目光投向了dubbox,dubbox是当当网基于dubbo二次开发的一个项目,dub ...
- vue清空input file
input file是只读的,给form一个id,用form.reset()干掉里面input的值 document.getElementById("uploadForm")&am ...
- 理解js中私有变量
私有变量在js中是个什么概念.当下我的认识是var所定义的变量,实际可以理解为属性和方法,或者单单是临时存储器,不归属任何对象. 一个声明函数: function a(){ var v = &quo ...
- 将已编写的静态的网页发布到github上
最近在学习前端框架的过程中,一直想把自己学习中做的demo 发布到github 上去.但是在查看了很多相关资料也没能找到一个比较满意的结果. 无奈之下,只能尝试做用了一种自认为最low 的方式来达到部 ...
- MS16-032提权正确方法
原版MS16-032提权会Spawn一个System Shell出来,只能通过Remote Desktop获取.这里修改exploit,直接反弹Shell.注意MS16-032依赖 thread ha ...