天天看點

python urllib2子產品_Python中urllib2子產品的8個使用細節分享

Python 标準庫中有很多實用的工具類,但是在具體使用時,标準庫文檔上對使用細節描述的并不清楚,比如 urllib2 這個 HTTP 用戶端庫。這裡總結了一些 urllib2 庫的使用細節。

1 Proxy 的設定

urllib2 預設會使用環境變量 http_proxy 來設定 HTTP Proxy。如果想在程式中明确控制 Proxy,而不受環境變量的影響,可以使用下面的方式

import urllib2

enable_proxy = True

proxy_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)

這裡要注意的一個細節,使用 urllib2.install_opener() 會設定 urllib2 的全局 opener。這樣後面的使用會很友善,但不能做更細粒度的控制,比如想在程式中使用兩個不同的 Proxy 設定等。比較好的做法是不使用 install_opener 去更改全局的設定,而隻是直接調用 opener 的 open 方法代替全局的 urlopen 方法。

2 Timeout 設定

在老版本中,urllib2 的 API 并沒有暴露 Timeout 的設定,要設定 Timeout 值,隻能更改 Socket 的全局 Timeout 值。

import urllib2

import socket

socket.setdefaulttimeout(10) # 10 秒鐘後逾時

urllib2.socket.setdefaulttimeout(10) # 另一種方式

在新的 Python 2.6 版本中,逾時可以通過 urllib2.urlopen() 的 timeout 參數直接設定。

import urllib2

response = urllib2.urlopen('http://www.google.com', timeout=10)

3 在 HTTP Request 中加入特定的 Header要加入 Header,需要使用 Request 對象:

import urllib2

request = urllib2.Request(uri)

request.add_header('User-Agent', 'fake-client')

response = urllib2.urlopen(request)

對有些 header 要特别留意,Server 端會針對這些 header 做檢查

1.User-Agent 有些 Server 或 Proxy 會檢查該值,用來判斷是否是浏覽器發起的 Request

2.Content-Type 在使用 REST 接口時,Server 會檢查該值,用來确定 HTTP Body 中的内容該怎樣解析。

常見的取值有:

1.application/xml :在 XML RPC,如 RESTful/SOAP 調用時使用

2.application/json :在 JSON RPC 調用時使用

3.application/x-www-form-urlencoded :浏覽器送出 Web 表單時使用

……

在使用 RPC 調用 Server 提供的 RESTful 或 SOAP 服務時, Content-Type 設定錯誤會導緻 Server 拒絕服務。

4 Redirect

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

import urllib2

response = urllib2.urlopen('http://www.google.cn')

redirected = response.geturl() == 'http://www.google.cn'

如果不想自動 Redirect,除了使用更低層次的 httplib 庫之外,還可以使用自定義的 HTTPRedirectHandler 類。

import urllib2

class RedirectHandler(urllib2.HTTPRedirectHandler):

def http_error_301(self, req, fp, code, msg, headers):

pass

def http_error_302(self, req, fp, code, msg, headers):

pass

opener = urllib2.build_opener(RedirectHandler)

opener.open('http://www.google.cn')

5 Cookie

urllib2 對 Cookie 的處理也是自動的。如果需要得到某個 Cookie 項的值,可以這麼做:

import urllib2

import cookielib

cookie = cookielib.CookieJar()

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

response = opener.open('http://www.google.com')

for item in cookie:

if item.name == 'some_cookie_item_name':

print item.value

6 使用 HTTP 的 PUT 和 DELETE 方法urllib2 隻支援 HTTP 的 GET 和 POST 方法,如果要使用 HTTP PUT 和 DELETE,隻能使用比較低層的 httplib 庫。雖然如此,我們還是能通過下面的方式,使 urllib2 能夠發出 HTTP PUT 或 DELETE 的包:

import urllib2

request = urllib2.Request(uri, data=data)

request.get_method = lambda: 'PUT' # or 'DELETE'

response = urllib2.urlopen(request)

這種做法雖然屬于 Hack 的方式,但實際使用起來也沒什麼問題。

7 得到 HTTP 的傳回碼

對于 200 OK 來說,隻要使用 urlopen 傳回的 response 對象的 getcode() 方法就可以得到 HTTP 的傳回碼。但對其它傳回碼來說,urlopen 會抛出異常。這時候,就要檢查異常對象的 code 屬性了:

import urllib2

try:

response = urllib2.urlopen('http://restrict.web.com')

except urllib2.HTTPError, e:

print e.code

8 Debug Log

使用 urllib2 時,可以通過下面的方法把 Debug Log 打開,這樣收發包的内容就會在螢幕上列印出來,友善我們調試,在一定程度上可以省去抓包的工作。

import urllib2

httpHandler = 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.com')