度过了一个冬眠,在春末夏初之际,补充自己的营养,努力学习,努力工作!
Python 标准库 urllib2 的使用细节
上一篇 /
下一篇 2014-07-07 18:05:43
/ 个人分类:python
A?{BJ _Q\0转自:http://zhuoqiang.me/python-urllib2-usage.html51Testing软件测试网&cB%Wcp+Yy
~ MOq0V
a
uD^*_051Testing软件测试网o
L?L0P2}y&]pPython 标准库中有很多实用的工具类,但是在具体使用时,标准库文档上对使用细节描述的并不清楚,比如 urllib2 这个 HTTP 客户端库。这里总结了一些 urllib2 的使用细节。
+b0uF+sF%Lm,q5s051Testing软件测试网O6v LS#j'f0]\h[urllib2 默认会使用环境变量http_proxy来设置 HTTP Proxy。如果想在程序中明确控制 Proxy 而不受环境变量的影响,可以使用下面的方式51Testing软件测试网LBh:RX/U$J R;Z
importurllib2enable_proxy=Trueproxy_handler=urllib2.ProxyHandler({"http":'http://some-proxy.com:8080'})null_proxy_handler=urllib2.ProxyHandler({})ifenable_proxy:opener=urllib2.build_opener(proxy_handler)else:opener=urllib2.build_opener(null_proxy_handler)urllib2.install_opener(opener)
-yP
y;x qZS(L'rb0这里要注意的一个细节,使用urllib2.install_opener()会设置 urllib2 的全局opener。这样后面的使用会很方便,但不能做更细粒度的控制,比如想在程序中使用两个不同的 Proxy 设置等。比较好的做法是不使用install_opener去更改全局的设置,而只是直接调用opener的open方法代替全局的urlopen方法。
*M8O3g c6j ~A d0
x*P4s/@7K6]l,~Yx9d0在老版 Python 中,urllib2 的 API 并没有暴露 Timeout 的设置,要设置 Timeout 值,只能更改 Socket 的全局 Timeout 值。
REVva9e:T0importurllib2importsocketsocket.setdefaulttimeout(10)# 10 秒钟后超时urllib2.socket.setdefaulttimeout(10)# 另一种方式
51Testing软件测试网7LMk\"L在 Python 2.6 以后,超时可以通过urllib2.urlopen()的timeout参数直接设置。
Ik8y1u~0importurllib2response=urllib2.urlopen('http://www.google.com',timeout=10)
51Testing软件测试网-t9R{N-xu8a6ch^nurllib2 默认情况下会针对 HTTP 3XX 返回码自动进行 redirect 动作,无需人工配置。要检测是否发生了 redirect 动作,只要检查一下Response的 URL 和Request的 URL 是否一致就可以了。
$`-`Be+u4?R,m#d0importurllib2response=urllib2.urlopen('http://www.google.cn')redirected=response.geturl()=='http://www.google.cn'
51Testing软件测试网:O.x%]jG}#B如果不想自动 redirect,除了使用更低层次的 httplib 库之外,还可以自定义HTTPRedirectHandler类。
+C'J5s&B1{^(}&Xh0importurllib2classRedirectHandler(urllib2.HTTPRedirectHandler):defhttp_error_301(self,req,fp,code,msg,headers):passdefhttp_error_302(self,req,fp,code,msg,headers):passopener=urllib2.build_opener(RedirectHandler)opener.open('http://www.google.cn')
51Testing软件测试网#|W9Wj$G"d:curllib2 对 Cookie 的处理也是自动的。如果需要得到某个 Cookie 项的值,可以这么做:
@b"| h0?;xn|O0importurllib2importcookielibcookie=cookielib.CookieJar()opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))response=opener.open('http://www.google.com')foritemincookie:ifitem.name=='some_cookie_item_name':printitem.value
s3}A4U8Z(i6^K0urllib2 只支持 HTTP 的GET和POST方法,如果要使用 HTTPPUT和DELETE,只能使用比较低层的 httplib 库。虽然如此,我们还是能通过下面的方式,使 urllib2 能够发出PUT或DELETE的请求:51Testing软件测试网^Hf;dI
importurllib2request=urllib2.Request(uri,data=data)request.get_method=lambda:'PUT'# or 'DELETE'response=urllib2.urlopen(request)
[8dr] o,q'D @^0这种做法虽然属于 Hack 的方式,但实际使用起来也没什么问题。51Testing软件测试网9d7lvw$v-?]
51Testing软件测试网R$f5Mo^:Eh
Zu对于200 OK来说,只要使用urlopen返回的response对象的getcode()方法就可以得到 HTTP 的返回码。但对其它返回码来说,urlopen 会抛出异常。这时候,就要检查异常对象的code属性了:51Testing软件测试网"?%gGOy K?
importurllib2try:response=urllib2.urlopen('http://restrict.web.com')excepturllib2.HTTPError,e:printe.code
51Testing软件测试网.}/IS{!D+?LL#[*o使用 urllib2 时,可以通过下面的方法把 debug Log 打开,这样收发包的内容就会在屏幕上打印出来,方便调试,有时可以省去抓包的工作51Testing软件测试网/F|(~6t'Tq:~;r
importurllib2httpHandler=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')51Testing软件测试网3i I1IF ~G
51Testing软件测试网WDs7m7W'zU
收藏
举报
TAG: