上一章我们了解了urllib2的两个重要概念,本章我们将深入了解urllib2
1.Proxy的设置
urllib2默认会使用环境变量http_proxy来设置HTTP Proxy
如果想在程序中明确控制Proxy而不受环境变量的影响,可以使用代理。
新建test14来实现一个简单的代理Demo:
- 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)
这里要注意的一个细节,使用urllib2.install_opener()会设置urllib2的全局opener。
这样后面的使用会很方便,但不能做更细致的控制,比如像在程序中使用两个不同的Proxy设置等。
比较好的做法是不使用install_opener去更改全局的设置,而只是直接调用opener的open方法代替全局的urlopen方法。
2.Timeout设置
在老版Python中(Python2.6前),urllib2的
API并没有暴露Timeout的设置,要设置Timeout值,只能更改Socket的全局Timeout值。
- import urllib2
- import socket
- socket.setdefaulttimeout(10) # 10 秒钟后超时
- urllib2.socket.setdefaulttimeout(10) # 另一种方式
在Python2.6以后,超市可以通过urllib2.urlopen()的Timeout参数直接设置
- import urllib2
- response = urllib2.urlopen('http://www.google.com', timeout=10)
3.HTTP Request中加入特定的Header
要加入header,需要使用Request对象:
- import urllib2
- request = urllib2.Request('http://www.baidu.com/')
- request.add_header('User-Agent', 'fake-client')
- response = urllib2.urlopen(request)
- print response.read()
User-Agent:有些服务器或Proxy会通过该值来判断是否是浏览器发出的请求
Content-Type:在使用REST接口时,服务器会检查该值,用来确定HTTP Body中的内容该怎样解析。常见的取值有:
application/xml:在XML RPC,如RESTful/SOAP调用时使用
application/json:在JSON RPC调用时使用
application/x-www-form-urlencoded:浏览器提交Web表单时使用
在使用服务器提供的RESTful或SOAP服务时,Content-Type设置错误会导致服务器拒绝服务。
4.Redirect
urllib2默认情况下会针对HTTP 3XX返回码自动进行redirect动作,无需人工配置。
要检测是否发生了redirect动作,只要检查一下Resonse的URL和Request的URL是否一致就可以了。
- import urllib2
- my_url = 'http://www.google.cn'
- response = urllib2.urlopen(my_url)
- redirected = response.geturl() == my_url
- print redirected
- my_url = 'http://rrurl.cn/b1UZuP'
- response = urllib2.urlopen(my_url)
- redirected = response.geturl() == my_url
- print redirected
如果不想自动redirect,除了使用更低层次的httplib库之外,还可以自定义HTTPRedirectHandler类。
- import urllib2
- class RedirectHandler(urllib2.HTTPRedirectHandler):
- def http_error_301(self, req, fp, code, msg, headers):
- print "301"
- pass
- def http_error_302(self, req, fp, code, msg, headers):
- print "303"
- pass
- opener = urllib2.build_opener(RedirectHandler)
- opener.open('http://rrurl.cn/b1UZuP')
5.Cookie
urllib2对Cookie的处理也是自动的。如果需要得到某个Cookie项的值,可以这么做:
- import urllib2
- import cookielib
- cookie = cookielib.CookieJar()
- opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
- response = opener.open('http://www.baidu.com')
- for item in cookie:
- print 'Name = '+item.name
- print 'Value = '+item.value
6.使用HTTP的PUT和DELETE方法
urllib2只支持HTTP的GET和POST方法,如果要使用HTTP PUT和DELETE,只能使用比较低层的httplib库。
虽然如此,我们还是能通过下面的方式,使urllib2能够发出PUT或DELETE的请求:
- import urllib2
- request = urllib2.Request(uri, data=data)
- request.get_method = lambda: 'PUT' # or 'DELETE'
- response = urllib2.urlopen(request)
7.得到HTTP的返回码
对于200 OK来说,只要使用urlopen返回的response对象的getcode()方法就可以得到HTTP的返回码。
但对其他返回马来说,urlopen会抛出异常。这时候,就要检查异常对象的code属性了:
- import urllib2
- try:
- response = urllib2.urlopen('http://bbs.csdn.net/why')
- except urllib2.HTTPError, e:
- print e.code
8.Debug Log
使用urllib2时,可以通过下面的方法把debug Log打开,这样收发包的内容就会在屏幕上打印出来,方便调试,有时可以省去抓包工作
- import urllib2
- httpHandler = urllib2.HTTPHandler(debuglevel=1)
- httpsHandler = urllib2.HTTPSHandler(debuglevel=1)
- opener = urllib2.build_opener(httpHandler, httpsHandler)
- urllib2.install_opener(opener)
- response = urllib2.urlopen('http://www.google.com')
9.表单的处理
登录必要填表,表单怎么填?
首先利用工具截取所要填表的内容。
比如我一般用firefox_httpfox插件来看看自己到底发送了些什么包。
以verycd为例,先找到自己发的POST请求,以及POST表单项。
可以看到verycd的话需要填username,password,continueURL,fk,login_submit这几项,其中fk是随机生成的(其实不太随机,看上去像是把epoch时间经过简单的编码生成的),需要从网页获取,也就是说得先访问一次网页,用正则表达式等工具截取返回数据中的fk项。
continueURI顾名思义可以随便写,login_submit是固定的,这从源码可以看出。还有username,password那就很显然了:
- # -*- coding: utf-8 -*-
- import urllib
- import urllib2
- postdata=urllib.urlencode({
- 'username':'汪小光',
- 'password':'why888',
- 'continueURI':'http://www.verycd.com/',
- 'fk':'',
- 'login_submit':'登录'
- })
- req = urllib2.Request(
- url = 'http://secure.verycd.com/signin',
- data = postdata
- )
- result = urllib2.urlopen(req)
- print result.read()
10.伪装成浏览器
某些网站反感爬虫的到访,于是对爬虫一律拒绝请求
这时候我们需要伪装成浏览器,这可以通过修改http包中的header来实现
- #…
- headers = {
- 'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
- }
- req = urllib2.Request(
- url = 'http://secure.verycd.com/signin/*/http://www.verycd.com/',
- data = postdata,
- headers = headers
- )
11.对付“反盗链”
某些站点有所谓的反盗链设置,其实说穿了很简单,
就是检查你发送请求的header里面,referer站点是不是他自己,
所以我们只需要像把headers的referer改成该网站即可,以cnbeta为例:
#... headers = { 'Referer':'http://www.cnbeta.com/articles' } #...headers是一个dict数据结构,你可以放入任何想要的header,来做一些伪装。
例如:有些网站喜欢读取header中的X-Forwarded-For来看看人家的真实IP,可以直接把X-Forwarded-For改了。