python的urllib2庫詳細使用說明

來源:互聯網
上載者:User

標籤:

 

一直以來技術群裡會有新入行的同學提問關於urllib和urllib2以及cookielib相關的問題。所以我打算在這裡總結一下,避免大家反覆回答同樣的問題浪費資源。

這篇屬於教程類的文字,如果你已經非常瞭解urllib2和cookielib那麼請忽略本篇。

首先從一段代碼開始,

#cookieimport urllib2import cookielibcookie = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))request = urllib2.Request(url=‘http://www.baidu.com/‘)request.add_header(‘User-Agent‘,‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1‘)response = opener.open(request)for item in cookie:        print item.value

很多同學說,我可以直接在openr.open()裡寫url,為什麼你要用request。其實我這麼寫就是為了整理一下一般使用urllib2構造請求的常用步驟。

 

初步,urllib2構造請求常用步驟(結合上面的代碼):

1、handler

handler既urllib2.build_opener(handler)中傳遞的對象參數,以下是官方的常用handler

urllib2.HTTPHandler() 通過HTTP開啟URL
urllib2.CacheFTPHandler() 具有持久FTP串連的FTP處理常式
urllib2.FileHandler() 開啟本地檔案
urllib2.FTPHandler() 通過FTP開啟URL
urllib2.HTTPBasicAuthHandler() 通過HTTP驗證處理
urllib2.HTTPCookieProcessor() 處理HTTP cookie
urllib2.HTTPDefaultErrorHandler() 通過引發HTTPError異常處理HTTP錯誤
urllib2.HTTPDigestAuthHandler() HTTP摘要驗證處理
urllib2.HTTPRedirectHandler() 處理HTTP重新導向
urllib2.HTTPSHandler() 通過安全HTTP重新導向
urllib2.ProxyHandler() 通過代理重新導向請求
urllib2.ProxyBasicAuthHandler 基本的代理驗證
urllib2.ProxyDigestAuthHandler 摘要代理驗證
urllib2.UnknownHandler 處理所有未知URL的處理常式

2、request

request=urllib2.Request(url=‘‘) 

request.add_data(data) 如果請求是HTTP,則方法改為POST。注意該方法不會將data追加到之前已經設定的任何資料上,而是使用現在的data替換之前的
request.add_header(key,val) key是前序名,val是包頭值,兩個參數都是字串
request.add_unredirected_header(key,val) 同上,但是不會添加到重新導向請求中
request.set_proxy(host,type) 準備請求到伺服器。使用host替換原來的主機,使用type替換原來的請求類型

3、opener 

基本的urlopen()函數不支援驗證、cookie或其他的HTTP進階功能。要支援這些功能,必須使用build_opener()函數來建立自己的自訂Opener對象

建自己的自訂Opener對象,通常有兩種方式:

a) 

opener=urllib2.OpenerDirector()
opener.add_handler(handler)

b)

opener=urllib2.OpenerDirector()
urllib2.build_opener(handler)
install_opener(opener)

安裝opener作為urlopen()使用的全域URL opener,即意味著以後調用urlopen()時都會使用安裝的opener對象。opener通常是build_opener()建立的opener對象。

4、content_stream

content_stream=opener.open(request)

5、content_stream.read()

通過以上5個步驟,你就可以得到和本篇開始處code差不多的代碼。這樣你就完成了一個urllib2基本使用方式的構造。你也可以將以上5個步驟封裝成類,但是我自己覺得並不是非常簡介。

urllib2模組不僅可以使用urlopen()函數還可以自訂opener來訪問網頁
但同時要注意:urlretrieve()函數是urllib模組中的,urllib2模組中不存在該函數。但是使用urllib2模組時一般都離不開urllib模組,因為post的資料需要使用urllib.urlencode()函數來編碼。

 

進階,urllib2更多使用細節:

1、Proxy的設定

import urllib2enable_proxy=Trueproxy_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)

ps:使用urllib2.install_opener()會設定urllib2的全域opener。這樣後面的使用會很方便,但不能做更細緻的控制,如果想在程式中使用兩個不同的proxy設定等。比較好的方法就是不適用install_opener去更改全域的設定,而只是直接調用opener的open方法代替全域的urlopen方法。

2、timeout設定

# < py2.6import urllib2import socketsocket.setdefaulttimeoust(10) #one wayurllib2.socket.setdefaulttimeout(10)#anther way# >=py2.6import urllib2response = urllib2.urlopen(‘http://www.google.com‘,timeout=10)

3、在http request中加入特定的header

要加入header,需要使用Request對象:

import urllib2request = urllib2.Request(url)request.add_header(‘User-Agent‘,‘fake-client‘)response = urllib2.urlopen(request)

對有些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表單時使用

4、Redirect

urllib2預設情況下會針對HTTP 3xx返回碼自動進行redirect動作,無需人工配置。要檢測是否發生了redirect動作,只要檢查一下Response的URL和Request的URL是否一直就可以了。

import urllib2response = urllib2.urlopen(‘http://www.g.cn‘)redirected = response.geturl() == ‘http://www.google.cn‘

如果不想自動redirect,除了使用更地層的httplib庫意外,還可以自訂HTTPRedirectHandler類。

import urllib2class RedirectHandler(urllib2.HTTPRedirectHandler):    def http_error_301(self,req,fp,code,msg,headers):        pass    def http_error_302(self,req,fp,code,msg,headers):        passopener = urllib2.build_opener(RedirectHandler)opener.open(‘http://www.google.cn‘)

5、cookie

urllib2對cookie的處理也是自動的。如果需要得到某個cookie的值,如下

import urllib2import cookielibcookie = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))response = opener.open(‘http://www.google.cn‘)for item in cookie:    print item.value

6、使用HTTP的PUT和DELETE方法

urllib2隻支援HTTP的GET和POST方法,如果要使用HTTP PUT和DELETE,只能使用比較低層的httplib庫。

import urllib2request = urllib2.Request(url,data=data)request.get_method=lambda:‘PUT‘#or ‘DELETE‘response = urllib2.urlopen(request)

7、得到HTTP的返回碼

對於200OK來說,只要使用urlopen返回的response對象的getcode()方法就可以得到HTTP的返回碼。對其他返回碼來說,urlopen會拋出異常。這時候,就要檢查異常對象的code了

import urllib2try:    response = urllib2.urlopen(‘http://www.google.cn‘)except urllib2.HTTPError, e:    print e.code

8、debug log

使用urllib2時,可以通過下面的方法把debug log開啟,這樣收發包的內容就會在螢幕上列印出了

import urllib2httpHandler=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.cn‘)

 

python的urllib2庫詳細使用說明

標籤:class   style   代碼   使用   問題   檔案   com   資料   log   

原文:http://www.cnblogs.com/kennyhr/p/4018668.html

python的urllib2庫詳細使用說明

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.