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. Caused by: java.io.IOException: Filesystem closed的处理

    org.apache.hadoop.hive.ql.metadata.HiveException: Unable to rename output from: hdfs://nameservice/u ...

  2. ListBox, ListView, GridView

    ListView是ListBox的派生类,而GridView是ViewBase的派生类 ListView的View属性是ViewBase,所以GridView可以作为ListView的属性 如 < ...

  3. uva 10683 Fill

    https://vjudge.net/problem/UVA-10603 题意: 倒水问题,输出最少的倒水量和目标水量 如果无解,目标水量就是尽可能接近给定点的目标水量,但不得大于给定的目标水量 推推 ...

  4. 九度OJ 1535 重叠的最长子串

    重叠的最长子串 http://ac.jobdu.com/problem.php?pid=1535 时间限制:1 秒 内存限制:128 兆 题目描述: 给定两个字符串,求它们前后重叠的最长子串的长度,比 ...

  5. ? 初识Webx 2

    初识Webx 1: http://www.cnblogs.com/lddbupt/p/5547189.html Webx Framework负责完成一系列基础性的任务. 比如系统初始化和响应请求. 系 ...

  6. Jmeter-分布式

    转载自: http://www.51testing.com/html/28/116228-247521.html 由于Jmeter本身的瓶颈,当需要模拟数以千计的并发用户时,使用单台机器模拟所有的并发 ...

  7. Quick-Cocos2dx-Community_3.6.3_Release 编译时libtiff.lib 无法解析

    Quick-Cocos2dx-Community_3.6.3_Release 使用VS2012编译,报错: libtiff.lib lnk2001 无法解析的外部符号 ltod3 类似于上面这种,刚才 ...

  8. Vue前端开发规范(山东数漫江湖)

    一.强制 1. 组件名为多个单词 组件名应该始终是多个单词的,根组件 App 除外. 正例: export default { name: 'TodoItem', // ... } 反例: expor ...

  9. VS推荐插件

    以下插件均可在NuGet下载 Smooth Scroll 平滑滚动 Format document on Save 保存时自动格式化代码 Supercharger VS增强插件[破解教程] HideM ...

  10. js_跑马灯

    跑马灯?刚听到这个词的时候,脑袋第一个想到的是跑马?嗯?就是香港的那种跑马场.懂?其次就是霓虹灯了,一闪一闪的多好看. 霓虹灯?哦,那是城市的杰作,记忆中是.开往城市边缘开,把车窗都摇下来,用速度换一 ...