[Python]网络爬虫(五):urllib2的使用细节与抓站技巧(转)

1.Proxy 的设置python

urllib2 默认会使用环境变量 http_proxy 来设置 HTTP Proxy。正则表达式

若是想在程序中明确控制 Proxy 而不受环境变量的影响,可使用代理。json

新建test14来实现一个简单的代理Demo:浏览器

[python]  view plain copy
 
  1. import urllib2  
  2. enable_proxy = True  
  3. proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})  
  4. null_proxy_handler = urllib2.ProxyHandler({})  
  5. if enable_proxy:  
  6.     opener = urllib2.build_opener(proxy_handler)  
  7. else:  
  8.     opener = urllib2.build_opener(null_proxy_handler)  
  9. urllib2.install_opener(opener)  

这里要注意的一个细节,使用 urllib2.install_opener() 会设置 urllib2 的全局 opener 。服务器

这样后面的使用会很方便,但不能作更细致的控制,好比想在程序中使用两个不一样的 Proxy 设置等。cookie

比较好的作法是不使用 install_opener 去更改全局的设置,而只是直接调用 opener 的 open 方法代替全局的 urlopen 方法。数据结构


2.Timeout 设置
在老版 Python 中(Python2.6前),urllib2 的 API 并无暴露 Timeout 的设置,要设置 Timeout 值,只能更改 Socket 的全局 Timeout 值。
app

[python]  view plain copy
 
  1. import urllib2  
  2. import socket  
  3. socket.setdefaulttimeout(10# 10 秒钟后超时  
  4. urllib2.socket.setdefaulttimeout(10# 另外一种方式  


在 Python 2.6 之后,超时能够经过 urllib2.urlopen() 的 timeout 参数直接设置。
socket

[python]  view plain copy
 
  1. import urllib2  
  2. response = urllib2.urlopen('http://www.google.com', timeout=10)  

 

 

3.在 HTTP Request 中加入特定的 Header工具

要加入 header,须要使用 Request 对象:

[python]  view plain copy
 
  1. import urllib2  
  2. request = urllib2.Request('http://www.baidu.com/')  
  3. request.add_header('User-Agent''fake-client')  
  4. response = urllib2.urlopen(request)  
  5. print response.read()  


对有些 header 要特别留意,服务器会针对这些 header 作检查
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 动做,只要检查一下 Response 的 URL 和 Request 的 URL 是否一致就能够了。

[python]  view plain copy
 
  1. import urllib2  
  2. my_url = 'http://www.google.cn'  
  3. response = urllib2.urlopen(my_url)  
  4. redirected = response.geturl() == my_url  
  5. print redirected  
  6.   
  7. my_url = 'http://rrurl.cn/b1UZuP'  
  8. response = urllib2.urlopen(my_url)  
  9. redirected = response.geturl() == my_url  
  10. print redirected  


若是不想自动 redirect,除了使用更低层次的 httplib 库以外,还能够自定义HTTPRedirectHandler 类。

[python]  view plain copy
 
  1. import urllib2  
  2. class RedirectHandler(urllib2.HTTPRedirectHandler):  
  3.     def http_error_301(self, req, fp, code, msg, headers):  
  4.         print "301"  
  5.         pass  
  6.     def http_error_302(self, req, fp, code, msg, headers):  
  7.         print "303"  
  8.         pass  
  9.   
  10. opener = urllib2.build_opener(RedirectHandler)  
  11. opener.open('http://rrurl.cn/b1UZuP')  

 

 

5.Cookie

urllib2 对 Cookie 的处理也是自动的。若是须要获得某个 Cookie 项的值,能够这么作:

[python]  view plain copy
 
  1. import urllib2  
  2. import cookielib  
  3. cookie = cookielib.CookieJar()  
  4. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))  
  5. response = opener.open('http://www.baidu.com')  
  6. for item in cookie:  
  7.     print 'Name = '+item.name  
  8.     print 'Value = '+item.value  

 

运行以后就会输出访问百度的Cookie值:

 

6.使用 HTTP 的 PUT 和 DELETE 方法

urllib2 只支持 HTTP 的 GET 和 POST 方法,若是要使用 HTTP PUT 和 DELETE ,只能使用比较低层的 httplib 库。虽然如此,咱们仍是能经过下面的方式,使 urllib2 可以发出 PUT 或DELETE 的请求:

[python]  view plain copy
 
  1. import urllib2  
  2. request = urllib2.Request(uri, data=data)  
  3. request.get_method = lambda'PUT' # or 'DELETE'  
  4. response = urllib2.urlopen(request)  

 

 

7.获得 HTTP 的返回码

对于 200 OK 来讲,只要使用 urlopen 返回的 response 对象的 getcode() 方法就能够获得 HTTP 的返回码。但对其它返回码来讲,urlopen 会抛出异常。这时候,就要检查异常对象的 code 属性了:

[python]  view plain copy
 
  1. import urllib2  
  2. try:  
  3.     response = urllib2.urlopen('http://bbs.csdn.net/why')  
  4. except urllib2.HTTPError, e:  
  5.     print e.code  



8.Debug Log

使用 urllib2 时,能够经过下面的方法把 debug Log 打开,这样收发包的内容就会在屏幕上打印出来,方便调试,有时能够省去抓包的工做

[python]  view plain copy
 
  1. import urllib2  
  2. httpHandler = urllib2.HTTPHandler(debuglevel=1)  
  3. httpsHandler = urllib2.HTTPSHandler(debuglevel=1)  
  4. opener = urllib2.build_opener(httpHandler, httpsHandler)  
  5. urllib2.install_opener(opener)  
  6. response = urllib2.urlopen('http://www.google.com')  

 

这样就能够看到传输的数据包内容了:

 

 

9.表单的处理

登陆必要填表,表单怎么填?

首先利用工具截取所要填表的内容。
好比我通常用firefox+httpfox插件来看看本身到底发送了些什么包。
以verycd为例,先找到本身发的POST请求,以及POST表单项。
能够看到verycd的话须要填username,password,continueURI,fk,login_submit这几项,其中fk是随机生成的(其实不太随机,看上去像是把epoch时间通过简单的编码生成的),须要从网页获取,也就是说得先访问一次网页,用正则表达式等工具截取返回数据中的fk项。continueURI顾名思义能够随便写,login_submit是固定的,这从源码能够看出。还有username,password那就很显然了:

 

[python]  view plain copy
 
  1. # -*- coding: utf-8 -*-  
  2. import urllib  
  3. import urllib2  
  4. postdata=urllib.urlencode({  
  5.     'username':'汪小光',  
  6.     'password':'why888',  
  7.     'continueURI':'http://www.verycd.com/',  
  8.     'fk':'',  
  9.     'login_submit':'登陆'  
  10. })  
  11. req = urllib2.Request(  
  12.     url = 'http://secure.verycd.com/signin',  
  13.     data = postdata  
  14. )  
  15. result = urllib2.urlopen(req)  
  16. print result.read()   

 

10.假装成浏览器访问
某些网站反感爬虫的到访,因而对爬虫一概拒绝请求
这时候咱们须要假装成浏览器,这能够经过修改http包中的header来实现

[python]  view plain copy
 
  1. #…  
  2.   
  3. headers = {  
  4.     'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  
  5. }  
  6. req = urllib2.Request(  
  7.     url = 'http://secure.verycd.com/signin/*/http://www.verycd.com/',  
  8.     data = postdata,  
  9.     headers = headers  
  10. )  
  11. #...  


11.对付"反盗链"
某些站点有所谓的反盗链设置,其实说穿了很简单,

 

就是检查你发送请求的header里面,referer站点是否是他本身,

因此咱们只须要像把headers的referer改为该网站便可,以cnbeta为例:

#...
headers = {
    'Referer':'http://www.cnbeta.com/articles'
}
#...

 

headers是一个dict数据结构,你能够放入任何想要的header,来作一些假装。

例如,有些网站喜欢读取header中的X-Forwarded-For来看看人家的真实IP,能够直接把X-Forwarde-For改了。

相关文章
相关标签/搜索