[Python]網路爬蟲(四):Opener與Handler,openerhandler
在開始後面的內容之前,先來解釋一下urllib2中的兩個個方法:info and geturl
urlopen返回的應答對象response(或者HTTPError執行個體)有兩個很有用的方法info()和geturl()
1.geturl():
geturl()返回擷取的真實的URL,這個很有用,因為urlopen(或者opener對象使用的)或許會有重新導向。擷取的URL或許跟請求URL不同。
以人人中的一個超級連結為例,
我們建一個urllib2_test10.py來比較一下原始URL和重新導向的連結:
[python] view plaincopy
- from urllib2 import Request, urlopen, URLError, HTTPError
-
-
- old_url = 'http://rrurl.cn/b1UZuP'
- req = Request(old_url)
- response = urlopen(req)
- print 'Old url :' + old_url
- print 'Real url :' + response.geturl()
運行之後可以看到真正的連結指向的網址:
2.info():
info()返回對象的字典對象,該字典描述了擷取的頁面情況。通常是伺服器發送的特定頭headers。
經典的headers包含"Content-length","Content-type",和其他內容。
我們建一個urllib2_test11.py來測試一下info的應用:
[python] view plaincopy
- from urllib2 import Request, urlopen, URLError, HTTPError
-
- old_url = 'http://www.baidu.com'
- req = Request(old_url)
- response = urlopen(req)
- print 'Info():'
- print response.info()
啟動並執行結果如下,可以看到頁面的相關資訊:
下面來說一說urllib2中的兩個重要概念:Openers和Handlers。
一、opener
urllib2.urlopen()函數不支援驗證、cookie或者其它HTTP進階功能。要支援這些功能,必須使用build_opener()(可以用於讓python程式類比瀏覽器進行訪問,作用你懂得~)函數建立自訂Opener對象。
用法如下
build_opener([handler1 [ handler2, ... ]])
參數handler是Handler執行個體,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。
build_opener ()返回的對象具有open()方法,與urlopen()函數的功能相同。
如果要修改http前序,可以用:
import urllib2opener = urllib2.build_opener()opener.addheaders = [('User-agent', 'Mozilla/5.0')]opener.open('http://www.example.com/')install_opener(opener)安裝不同的opener對象作為urlopen()使用的全域opener。
密碼驗證(HTTPBasicAuthHandler)HTTPBasicAuthHandler()處理常式可用add_password()來設定密碼。
h.add_password(realm,uri,user,passwd)
realm是與驗證相關聯的名稱或描述資訊,取決於遠程伺服器。uri是基URL。user和passwd分別指定使用者名稱和密碼。
import urllib2auth=urllib2.HTTPBasicAuthHandler()auth.add_password('Administrator','http://www.example.com','Dave','123456')opener=urllib2.build_opener(auth)u=opener.open('http://www.example.com/evilplan.html')Cookie處理(HTTPCookieProcessor)
import urllib2,cookielibcookie=cookielib.CookieJar()cookiehand=urllib2.HTTPCookieProcessor(cookie)opener=urllib2.build_opener(cookiehand)
代理(ProxyHandler)
ProxyHandler(proxies)參數proxies是一個字典,將協議名稱(http,ftp)等映射到相應Proxy 伺服器的URL。
proxy=ProxyHandler({'http':'http://someproxy.com:8080'})auth=HTTPBasicAuthHandler()auth.add_password()opener=build_opener(auth,proxy)也可以在urlopen中使用代理
import urllib2 proxy = 'http://%s:%s@%s' % ('userName', 'password', 'proxy') inforMation = urllib2.urlopen("http://www.example.com", proxies={'http':proxy})
二、Handler
handler用於處理URL,例如HTTP重新導向、HTTP cookies等。
如果你希望建立一個特定的openers,例如擷取一個能處理cookie的opener,或者擷取一個不重新導向的opener,就需要用到自訂handler。
Basic Authentication 基本驗證為了展示建立和安裝一個handler,我們將使用HTTPBasicAuthHandler。
通常驗證時,伺服器發送一個header(401錯誤碼) 請求驗證。這個指定了scheme 和一個‘realm’,其格式為:www-authenticate: SCHEME realm="REALM".
舉個執行個體:www-authenticate: Basic realm="cPanel Users"
用戶端必須使用新的請求,並在要求標頭裡包含正確的姓名和密碼。
為了簡化這個過程,我們可以建立一個HTTPBasicAuthHandler的執行個體,並讓opener使用這個handler就可以啦。
HTTPBasicAuthHandler使用一個密碼管理的對象來處理URLs和realms來映射使用者名稱和密碼。
如果你知道realm(從伺服器發送來的頭裡)是什麼,你就能使用HTTPPasswordMgr。
如果不關心realm是什麼,就可以使用HTTPPasswordMgrWithDefaultRealm。
代碼如下:
[python] view plaincopy
- # -*- coding: utf-8 -*-
- import urllib2
-
- # 建立一個密碼管理
- password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
- # 添加使用者名稱和密碼
-
- top_level_url = "http://example.com/foo/"
- password_mgr.add_password(None, top_level_url,'why', '1223')
-
- # 建立了一個新的handler
- handler = urllib2.HTTPBasicAuthHandler(password_mgr)
-
- # 建立 "opener" (OpenerDirector 執行個體)
- opener = urllib2.build_opener(handler)
-
- a_url = 'http://www.baidu.com/'
-
- # 使用 opener 擷取一個URL
- opener.open(a_url)
-
- # 安裝 opener.
- # 現在所有調用 urllib2.urlopen 將用我們的 opener.
- urllib2.install_opener(opener)
-
-
注意:除了HHTPBasicAuthHandler以外,ProxyHandler,UnknownHandler,HTTPHandler,HTTPDefaultErrorHandler, HTTPRedirectHandler,FTPHandler, FileHandler, HTTPErrorProcessor均會返回Handler。
歡迎收聽我的公眾號