urllib与urllib2:html
urllib2能够接受一个Request类的实例来设置URL请求的headers,urllib仅能够接受URL。这意味着,你不能够假装你的User Agent字符串等。python
urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。web
转载自 http://www.cnblogs.com/yuxc/archive/2011/08/01/2123995.htmljson
Python 标准库中有不少实用的工具类,可是在具体使用时,标准库文档上对使用细节描述的并不清楚,好比 urllib2 这个 HTTP 客户端库。这里总结了一些 urllib2 库的使用细节。浏览器
urllib2 默认会使用环境变量 http_proxy 来设置 HTTP Proxy。若是想在程序中明确控制 Proxy,而不受环境变量的影响,可使用下面的方式cookie
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 方法。app
在老版本中,urllib2 的 API 并无暴露 Timeout 的设置,要设置 Timeout 值,只能更改 Socket 的全局 Timeout 值。socket
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) |
要加入 Header,须要使用 Request 对象:post
import urllib2 request = urllib2.Request(uri) request.add_header('User-Agent', 'fake-client') response = urllib2.urlopen(request) |
对有些 header 要特别留意,Server 端会针对这些 header 作检查
常见的取值有:
application/x-www-form-urlencoded :浏览器提交 Web 表单时使用
在使用 RPC 调用 Server 提供的 RESTful 或 SOAP 服务时, Content-Type 设置错误会致使 Server 拒绝服务。
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') |
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 |
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 的方式,但实际使用起来也没什么问题。
对于 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 |
使用 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') |