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时支持延迟访问访问文件,即只有在需要时才读取文件或在文件中存储数据。

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实例。

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实例。

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 NoneValueError 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模块的更多相关文章

  1. 【转】cookielib模块

    cookielib模块 cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源.例如可以利用本模块 的CookieJar类的对象来 ...

  2. python—cookielib模块对cookies的操作

    最近用python写爬虫爬了点数据,确实是很好用的东西,今天对python如何操作cookie进行一下总结. python内置有cookielib模块操作cookie,配合urllib模块就可以了很轻 ...

  3. cookielib模块基础学习

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' import cookielib #主要用于处理http客户端的co ...

  4. Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块

    Python第十三天   django 1.6   导入模板   定义数据模型   访问数据库   GET和POST方法    SimpleCMDB项目   urllib模块   urllib2模块 ...

  5. cookielib模块 for python3

    python2 可以直接安装cookielib模块 而py3却不能安装 故需要安装http模块 举例子: from http import cookiejar cookie = cookiejar.C ...

  6. Python3使用cookielib模块

    同时使用过python2和python3的应该都知道,好多模块在python2中能直接安装,但是到了python3中却无法安装直接使用,同样python3中的好些模块在python2中也是一样 如下: ...

  7. Python cookielib 模块

    什么是 cookie : 指某些网站为了辨别用户身份,进行 session 跟踪而储存在用户本地终端上的数据,通常以 txt 文件形式存储.比如你登录了淘宝,浏览器就会保存 cookie 信息,这样我 ...

  8. python urllib、urlparse、urllib2、cookielib

    1.urllib模块 1.urllib.urlopen(url[,data[,proxies]]) 打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作.本例试着打开google i ...

  9. Python第十五天 datetime模块 time模块 thread模块 threading模块 Queue队列模块 multiprocessing模块 paramiko模块 fabric模块

    Python第十五天  datetime模块 time模块   thread模块  threading模块  Queue队列模块  multiprocessing模块  paramiko模块  fab ...

随机推荐

  1. XSS攻击处理方案

    1. XSS攻击基本概念 XSS是一种经常出现在web应用中的计算机安全漏洞,它允许恶意web用户将代码植入到提供给其它用户使用的页面中.比如这些代码包括HTML代码和客户端脚本.攻击者利用XSS漏洞 ...

  2. Linux下find命令及其参数的使用

    find命令原理:从指定的起始目录开始,递归地搜索其各个子目录,查找满足寻找条件的文件,并可以对其进行相关的操作. 格式:find [查找目录] [参数] [匹配模型] 多参数格式:find [查找目 ...

  3. 【bzoj1593-预定旅馆】线段树维护连续区间

    题解: 这题非常经典啊似乎..经典模型要记住啊.. 对于每个节点维护该区间里的最大的连续区间,然后我们就可以logn递归找最前面的一段. 那就维护mx(无限制),lmx(必须从左边开始),rmx(必须 ...

  4. 【NOIP】提高组2016 愤怒的小鸟

    [题意]Universal Online Judge [算法]状态压缩型DP [题解]看数据范围大概能猜到是状压了. 根据三点确定一条抛物线,枚举两个点之间的抛物线,再枚举有多少点在抛物线上(压缩为状 ...

  5. 【BZOJ】1584: [Usaco2009 Mar]Cleaning Up 打扫卫生

    [算法]DP+数学优化 [题意]把n个1~m的数字分成k段,每段的价值为段内不同数字个数的平方,求最小总价值.n,m,ai<=40000 [题解] 参考自:WerKeyTom_FTD 令f[i] ...

  6. Python与RPC -- (转)

    XML-RPC xmlrpc是使用http协议做为传输协议的rpc机制,使用xml文本的方式传输命令和数据. 一个rpc系统,必然包括2个部分: 1)rpc client,用来向rpc server调 ...

  7. Spring Boot:定制自己的starter

    在学习Spring Boot的过程中,接触最多的就是starter.可以认为starter是一种服务——使得使用某个功能的开发者不需要关注各种依赖库的处理,不需要具体的配置信息,由Spring Boo ...

  8. Python第三方库wordcloud(词云)快速入门与进阶

    前言: 笔主开发环境:Python3+Windows 推荐初学者使用Anaconda来搭建Python环境,这样很方便而且能提高学习速度与效率. 简介: wordcloud是Python中的一个小巧的 ...

  9. mssql手工注入1

    强制字符转成数字, 所以报错, 能获得数据 查版本号: http: -- 查数据库版本: http: -- 查当前数据库用户(如果看到dbo 那么多半当前数据库的用户是dba权限): http: -- ...

  10. LeetCode 19 Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...