通过python 的 urllib2 模块,可以轻易的去模拟用户访问网页的行为。
这里将自己的学习过程简单的记录下来。
一、urlopen函数
urlopen(url, data=None) -- Basic usage is the same as original
urllib. pass the url and optionally data to post to an HTTP URL, and
get a file-like object back. One difference is that you can also pass
a Request instance instead of URL. Raises a URLError (subclass of
IOError); for HTTP errors, raises an HTTPError, which can also be
treated as a valid response.
它的基本用法同urllib 库中的用法是一样的。urllib 中的urlopen 的注释如下:
urlopen(url, data=None, proxies=None)
Create a file-like object for the specified URL to read from.
但不同于urllib 的是,urllib2 中的urlopen函数的第一个参数url 可以是一个Request 实例。
1、基本用法
Example:
#等同urllib 中的urlopen 函数的用法
In [12]: response = urllib2.urlopen('http://www.baidu.com')
In [13]: response.read()
# urllib2 中的使用request 实例的用法
In [14]: request = urllib2.Request('http://www.baidu.com')
urllib2.urlopen('http://www.baidu.com',timeout=10)
二、opener(OpenerDirector)
The OpenerDirector manages a collection of Handler objects that do
all the actual work. Each Handler implements a particular protocol or
option. The OpenerDirector is a composite object that invokes the
Handlers needed to open the requested URL. For example, the
HTTPHandler performs HTTP GET and POST requests and deals with
non-error returns. The HTTPRedirectHandler automatically deals with
HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
deals with digest authentication
干嘛用的? 管理了一系列的handler 对象。我这这么理解的,其实我们在使用urlopen 的时候就已经存在了一个默认的handler 。只是对我们时透明的。我们可以使用这个handler做GET/POST 请求,但是如果我们想做一些其他的事情呢? 如我们想设置代理去做一些事情等所有非GET/POST能处理好的。那么我们就需要更换handler了 。这时就要使用opener ,这就时opener 所能干的。
1、设置代理
import urllib2
proxy_handler = urllib2.ProxyHandler({"http" : 'http://11.11.11.11:8080'})