標籤:
1. urllib2的opener和handler概念 1.1
Openers:
當你擷取一個URL你使用一個opener(一個urllib2.OpenerDirector的執行個體)。正常情況下,我們使用預設opener:通過urlopen。但你能夠建立個性的openers。可以用build_opener來建立opener對象。一般可用於需要處理cookie或者不想進行redirection的應用情境(You will want to create openers if you want to fetch URLs with specific handlers installed, for example to get an opener that handles cookies, or to get an opener that does not handle redirections.)
以下是用代理ip類比登入時(需要處理cookie)使用handler和opener的具體流程。
1 self.proxy = urllib2.ProxyHandler({‘http‘: self.proxy_url})2 self.cookie = cookielib.LWPCookieJar()3 self.cookie_handler = urllib2.HTTPCookieProcessor(self.cookie)4 self.opener = urllib2.build_opener(self.cookie_handler, self.proxy, urllib2.HTTPHandler)
1.2 Handles:
Openers使用處理器handlers,所有的“繁重”工作由handlers處理。每個handlers知道如何通過特定協議開啟URLs,或者如何處理URL開啟時的各個方面。例如HTTP重新導向或者HTTP cookies。
更多關於Openers和Handlers的資訊。http://www.voidspace.org.uk/python/articles/urllib2.shtml#openers-and-handlers
2. urllib2的提示 2.1 proxy代理ip建立opener
Note:Currently urllib2 does not support fetching of https locations through a proxy. This can be a problem.http://www.voidspace.org.uk/python/articles/urllib2.shtml#proxies
1 import urllib22 proxy——handler = urllib2.ProxyHandler({‘http‘: ‘54.186.78.110:3128‘})#注意要確保該代理ip可用,樣本中ip在美國3 opener = urllib2.build_opener(proxy_handler) 4 request = urllib2.Request(url, post_data, login_headers)#該例中還需要提交post_data和header資訊5 response = opener.open(request)6 print response.read().encode(‘utf-8‘) 2.2 用timeout參數設定逾時
1 import urllib22 response = urllib2.urlopen(‘http://www.google.com‘, timeout=10)
2.3 偽裝瀏覽器
有些網站的伺服器會檢查請求的header資訊,在訪問一些網站時,會出現HTTPError: HTTP Error 403: Forbidden這樣的異常,這是由於現在有些網站禁止爬蟲訪問,爬蟲會帶來伺服器上的負擔,爬蟲和瀏覽器發出的http請求區別在於:當使用者發送一個http請求的時候,瀏覽的的版本資訊也包含在了http請求資訊中,而爬蟲就不包含頭資訊,當伺服器端收到一個頁面訪問請求時,如果不知道發送這個請求使用的瀏覽器,作業系統,硬體平台等資訊,這些資訊在HTTP協議的中的一個欄位User-agent中,缺失這些資訊,伺服器會認為這些請求是非正常的訪問,我們用Fiddler工具就可以看到瀏覽器的請求的資訊。可以用urllib2中Request方法傳遞header來解決。
下例中提交了header中的User-Agent資訊,由此偽裝成瀏覽器發送請求。查看User-Agent資訊非常方便,可以使用Chrome瀏覽器F12審查元素看network中的Request Header可見詳細的Header資訊。
對付“反盜鏈”,有些網站會檢查header中的Referer是不是該網站本身,可以設定header時進行設定。
1 headers = {2 ‘User-Agent‘: ‘Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6‘,3 ‘referer‘: ‘https://login.taobao.com/member/login.jhtml?redirectURL=https%3A%2F%2Fwww.taobao.com%2F‘4 }5 request = urllib2.Request(6 url ="https://login.taobao.com/member/login.jhtml?redirectURL=https%3A%2F%2Fwww.taobao.com%2F",7 data = postdata,8 headers = headers9 )
更多關於HTTP header的詳細資料:http://rlog.cn/?p=521
2.4 cookie的使用
Cookie,指某些網站為了辨別使用者身份、進行session跟蹤而儲存在使用者本地終端上的資料(通常經過加密)。比如說有些網站需要登入後才能訪問某個頁面,在登入之前,你想抓取某個頁面內容是不允許的。那麼我們可以利用Urllib2庫儲存我們登入的Cookie,然後再抓取其他頁面就達到目的了。
cookie的一個使用樣本如下。
1 import urllib2 2 import cookielib 3 #聲明一個CookieJar對象執行個體來儲存cookie 4 cookie = cookielib.CookieJar() 5 #利用urllib2庫的HTTPCookieProcessor對象來建立cookie處理器 6 handler=urllib2.HTTPCookieProcessor(cookie) 7 #通過handler來構建opener 8 opener = urllib2.build_opener(handler) 9 #此處的open方法同urllib2的urlopen方法,也可以傳入request10 response = opener.open(‘http://www.baidu.com‘)11 for item in cookie:12 print ‘Name = ‘+item.name13 print ‘Value = ‘+item.value
2.5 urllib2.urlopen的返回碼
在無異常拋出的情況下,可以用getcode()方法來得到狀態代碼,所以需要異常處理。
1 import urllib2 2 try: 3 request = urllib2.Request(url) 4 response = urllib2.urlopen(request) 5 print response.read().decode(‘utf-8‘) 6 except urllib2.URLError, e: 7 if hasattr(e, "code"): 8 print e.code 9 if hasattr(e, "reason"):10 print e.reason
參考連結:
http://blog.csdn.net/pleasecallmewhy/article/details/8925978
原文地址:http://www.cnblogs.com/wuwenyan/p/4749018.html
【Python爬蟲學習筆記(1)】urllib2庫相關知識點總結