[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改了。

相關文章
相關標籤/搜索