Python 標準庫 urllib2 的使用細節

Python 標準庫中有不少實用的工具類,可是在具體使用時,標準庫文檔上對使用細節描述的並不清楚,好比 urllib2 這個 HTTP 客戶端庫。這裏總結了一些 urllib2 的使用細節。 html

  • Proxy 的設置
  • Timeout 設置
  • 在 HTTP Request 中加入特定的 Header
  • Redirect
  • Cookie
  • 使用 HTTP 的 PUT 和 DELETE 方法
  • 獲得 HTTP 的返回碼
  • Debug Log

Proxy 的設置

urllib2 默認會使用環境變量http_proxy來設置 HTTP Proxy。若是想在程序中明確控制 Proxy 而不受環境變量的影響,可使用下面的方式 python

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方法。 web


Timeout 設置

在老版 Python 中,urllib2 的 API 並無暴露 Timeout 的設置,要設置 Timeout 值,只能更改 Socket 的全局 Timeout 值。 json

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)

在 HTTP Request 中加入特定的 Header

要加入 header,須要使用Request對象: 服務器

import urllib2

request = urllib2.Request(uri)
request.add_header('User-Agent', 'fake-client')
response = urllib2.urlopen(request)

對有些 header 要特別留意,服務器會針對這些 header 作檢查 cookie

  • User-Agent: 有些服務器或 Proxy 會經過該值來判斷是不是瀏覽器發出的請求 app

  • Content-Type: 在使用 REST 接口時,服務器會檢查該值,用來肯定 HTTP Body 中的內容該怎樣解析。常見的取值有: socket

    • application/xml: 在 XML RPC,如 RESTful/SOAP 調用時使用
    • application/json: 在 JSON RPC 調用時使用
    • application/x-www-form-urlencoded: 瀏覽器提交 Web 表單時使用

    在使用服務器提供的 RESTful 或 SOAP 服務時,Content-Type設置錯誤會致使服務器拒絕服務 工具

Redirect

urllib2 默認狀況下會針對 HTTP 3XX 返回碼自動進行 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')

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

使用 HTTP 的 PUT 和 DELETE 方法

urllib2 只支持 HTTP 的GET和POST方法,若是要使用 HTTPPUT和DELETE,只能使用比較低層的 httplib 庫。雖然如此,咱們仍是能經過下面的方式,使 urllib2 可以發出PUT或DELETE的請求:

import urllib2

request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'PUT' # or 'DELETE'
response = urllib2.urlopen(request)

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

獲得 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

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')
相關文章
相關標籤/搜索