`
wwty
  • 浏览: 536679 次
  • 性别: Icon_minigender_1
  • 来自: 北京-郑州
社区版块
存档分类
最新评论

httplib,urllib和urllib2的了解学习

阅读更多

httplib — HTTP protocol client:
This module defines classes which implement the client side of the HTTP and HTTPS protocols. It is
normally not used directly — the module urllib uses it to handle URLs that use HTTP and HTTPS.
这是python API当中关于httplib的介绍,意思是:
这个组件实现了HTTP和HTTPS的客户端协议,它通常不被直接使用----urilib使用它控制URLs用于HTTP和HTTPS

 

urllib和urllib2:

urllib 和urllib2实现的功能大同小异,但urllib2要比urllib功能等各方面更高一个层次。目前的HTTP访问大部分都使用urllib2来进行访问

 

urllib2:

req = urllib2.Request('http://wwty.iteye.com')     
response = urllib2.urlopen(req)     
the_page = response.read()  

 FTP同样:

req = urllib2.Request('ftp://wwty.iteye.com')

urlopen返回的应答对象response有两个很有用的方法info()和geturl()
geturl -- 这个返回获取的真实的URL,这个很有用,因为urlopen(或者opener对象使用的)或许
会有重定向。获取的URL或许跟请求URL不同。

 

Data数据
有时候你希望发送一些数据到URL
post方式:

values ={'body' : 'test short talk','via':'xxxx'} 
data = urllib.urlencode(values)
req = urllib2.Request(url, data)

get方式:

data['name'] = 'Somebody Here'  
data['location'] = 'Northampton'  
data['language'] = 'Python'  
url_values = urllib.urlencode(data)
url = 'http://www.example.com/example.cgi'  
full_url = url + '?' + url_values   
data = urllib2.open(full_url) 

 

URLError--HTTPError:

from urllib2 import Request, urlopen, URLError, HTTPError
req = Request(someurl)
try:
     response = urlopen(req)
except HTTPError, e:
     print 'Error code: ', e.code
except URLError, e:
     print 'Reason: ', e.reason
else:
      .............

 或者:

from urllib2 import Request, urlopen, URLError
req = Request(someurl)
try:
     response = urlopen(req)
except URLError, e:
     if hasattr(e, 'reason'):
           print 'Reason: ', e.reason
     elif hasattr(e, 'code'):
           print 'Error code: ', e.code
     else:
           .............

通常,URLError在没有网络连接(没有路由到特定服务器),或者服务器不存在的情况下产生
异常同样会带有"reason"属性,它是一个tuple,包含了一个错误号和一个错误信息
req = urllib2.Request('http://www.pretend_server.org')
try:
   urllib2.urlopen(req)
except URLError, e:  
   print e.reason
   print e.code
   print e.read()

最后需要注意的就是,当处理URLError和HTTPError的时候,应先处理HTTPError,后处理URLError

 

Openers和Handlers:
opener使用操作器(handlers)。所有的重活都交给这些handlers来做。每一个handler知道
怎么打开url以一种独特的url协议(http,ftp等等),或者怎么处理打开url的某些方面,如,HTTP重定向,或者HTTP
cookie。
默认opener有对普通情况的操作器 (handlers)- ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor.
再看python API:Return an OpenerDirector instance, which chains the handlers in the order given
这就更加证明了一点,那就是opener可以看成是一个容器,这个容器当中放的是控制器,默认的,容器当中有五个控制
器,程序员也可以加入自己的控制器,然后这些控制器去干活。

class HTTPHandler(AbstractHTTPHandler):
    def http_open(self, req):
        return self.do_open(httplib.HTTPConnection, req)
    http_request = AbstractHTTPHandler.do_request_

HTTPHandler是Openers当中的默认控制器之一,看到这个代码,证实了urllib2是借助于httplib实现的,同时也证实了Openers和Handlers的关系。

分享到:
评论
1 楼 laputa 2010-03-18  
博主写的很好,学习了。
另,get方式的代码最后一行有小问题:
data = urllib2.open(full_url)  
应为urlopen

相关推荐

Global site tag (gtag.js) - Google Analytics