python基于http协议编程:httplib,urllib和urllib2

转自:http://www.cnblogs.com/chenzehe/archive/2010/08/30/1812995.html

python基于http协议编程:httplib,urllib和urllib2

        httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现。

import  httplib
conn 
=  httplib.HTTPConnection( " google.com " )
conn.request(
' get ' ' / ' )
print  conn.getresponse().read()
conn.close()

 

 

httplib.HTTPConnection ( host [ , port [ , strict [ , timeout ]]] )

 

       HTTPConnection类的构造函数,表示一次与服务器之间的交互,即请求/响应。参数host表示服务器主机,如:http://www.csdn.net/;port为端口号,默认值为80; 参数strict的 默认值为false, 表示在无法解析服务器返回的状态行时( status line) (比较典型的状态行如: HTTP/1.0 200 OK ),是否抛BadStatusLine 异常;可选参数timeout 表示超时时间。
HTTPConnection提供的方法:

HTTPConnection.request ( method , url [ , body [ , headers ]] )

 

调用request 方法会向服务器发送一次请求,method 表示请求的方法,常用有方法有get 和post ;url 表示请求的资源的url ;body 表示提交到服务器的数据,必须是字符串(如果method 是”post” ,则可以把body 理解为html 表单中的数据);headers 表示请求的http 头。
HTTPConnection.getresponse ()
获取Http 响应。返回的对象是HTTPResponse 的实例,关于HTTPResponse 在下面 会讲解。
HTTPConnection.connect ()
连接到Http 服务器。
HTTPConnection.close ()
关闭与服务器的连接。
HTTPConnection.set_debuglevel ( level )
设置高度的级别。参数level 的默认值为0 ,表示不输出任何调试信息。
httplib.HTTPResponse
HTTPResponse表示服务器对客户端请求的响应。往往通过调用HTTPConnection.getresponse()来创建,它有如下方法和属性:
HTTPResponse.read([amt])
获取响应的消息体。如果请求的是一个普通的网页,那么该方法返回的是页面的html。可选参数amt表示从响应流中读取指定字节的数据。
HTTPResponse.getheader(name[, default])
获取响应头。Name表示头域(header field)名,可选参数default在头域名不存在的情况下作为默认值返回。
HTTPResponse.getheaders()
以列表的形式返回所有的头信息。
HTTPResponse.msg
获取所有的响应头信息。
HTTPResponse.version
获取服务器所使用的http协议版本。11表示http/1.1;10表示http/1.0。
HTTPResponse.status
获取响应的状态码。如:200表示请求成功。
HTTPResponse.reason
返回服务器处理请求的结果说明。一般为”OK”
下面通过一个例子来熟悉HTTPResponse中的方法:

   
   
复制代码
import  httplib
conn 
=  httplib.HTTPConnection( " www.g.com " 80 , False)
conn.request(
' get ' ' / ' , headers  =  { " Host " " www.google.com " ,
                                    
" User-Agent " " Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5 " ,
                                    
" Accept " " text/plain " })
res 
=  conn.getresponse()
print   ' version: ' , res.version
print   ' reason: ' , res.reason
print   ' status: ' , res.status
print   ' msg: ' , res.msg
print   ' headers: ' , res.getheaders()
# html
#
print '\n' + '-' * 50 + '\n'
#
print res.read()
conn.close()
复制代码

 

Httplib模块中还定义了许多常量,如:
Httplib. HTTP_PORT 的值为80,表示默认的端口号为80;
Httplib.OK 的值为200,表示请求成功返回;
Httplib. NOT_FOUND 的值为404,表示请求的资源不存在;
可以通过httplib.responses 查询相关变量的含义,如:
Print httplib.responses[httplib.NOT_FOUND] #not found
更多关于httplib的信息,请参考Python手册httplib 模块。

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

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

 

FTP同样:

 

req  =  urllib2.Request( ' ftp://pythoneye.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://pythoneye.com/example.cgi '
full_url 
=  url  +   ' ? '   +  url_values
data 
=  urllib2.open(full_url)
复制代码

 

使用Basic HTTP Authentication:

   
   
复制代码
import  urllib2
#  Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler  =  urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm
= ' PDQ Application ' ,
                          uri
= ' https://pythoneye.com/vecrty.py ' ,
                          user
= ' user ' ,
                          passwd
= ' pass ' )
opener 
=  urllib2.build_opener(auth_handler)
#  ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen(
' http://www. pythoneye.com/app.html ' )
复制代码

 

使用代理ProxyHandler:

   
   
复制代码
proxy_handler  =  urllib2.ProxyHandler({ ' http ' ' http://www.example.com:3128/ ' })
proxy_auth_handler 
=  urllib2.HTTPBasicAuthHandler()
proxy_auth_handler.add_password(
' realm ' ' host ' ' username ' ' password ' )

opener 
=  build_opener(proxy_handler, proxy_auth_handler)
#  This time, rather than install the OpenerDirector, we use it directly:
opener.open( ' http://www.example.com/login.html ' )

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://pythoneye.com ' )
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的关系。


python urllib2 (转)

当处理HTTP链接的时候,链接如果有中文的话,那么发起HTTP链接的时候,一定要先把URL编码,否则就会出现问题。而在python中,用 urllib2.quote(URL)进入编码和urllib2.unquote(URL)解码的时候,有一点需要注意,就是URL字符串不能是 unicode编码,此时必须把URL编码转换成适当的编码,如utf-8或gb2312等而python处理编码转换的机制如下:原来编码》内部编码》 目的编码 python的内部编码是使用unicode来处理的 gb=”中国”#此处为原本gb2312编码 uni=unicode(gb,’gb2312′)#把gb2312编码转换成unicode的内部编码 utf=uni.encode(’utf-8′)#把unicode编码转换成utf-8目的编码在处理wxpython文本框的时候要注意,默认的编码 是unicode编码,利用urllib.quote编码时候,可以通过如下方面转换后,再进行 URL编码 URL=wxpython文本框原本的unicode编码 URL=URL.encode(’utf-8′)#把unicode编码转换成utf-8编码 URL=urllib2.quote(URL)#进入URL编码,以便HTTP链接

对我来说,Python里面哪个模块用的最多,恐怕urllib2这个不是第一也得算前三了。先看下下面最常用的代码
Python语言:

import urllib2
req = urllib2.Request("http://www.g.cn")

res = urllib2.urlopen( req )
html = res.read()
res.close()

这里可以通过urllib2进行抓取页面 。也可以直接使用urllib2.urlopen( http://www.g.cn),通过Reques对象打开的好处是,我们可以很方便的为Reques 添加HTTP 请求的头部信息。
Python语言:
import urllib2
req = urllib2.Request("http://www.g.cn")
req.add_header( "Cookie" , "aaa=bbbb" ) # 这里通过add_header方法很容易添加的请求头
req.add_header( "Referer", "http://www.fayaa.com/code/new/" )
res = urllib2.urlopen( req )
html = res.read()
res.close()

headers 初始化为{} ,所有如果连续执行两次req.add_header( "Cookie" , "aaa=bbbb" ) , 则后面的值会把前面的覆盖掉
class Request:
    def __init__(self, url, data=None, headers={},
                 origin_req_host=None, unverifiable=False):



当执行 res = urllib2.urlopen( req ) 时

_opener = None
def urlopen(url, data=None):
    global _opener
    if _opener is None:
        _opener = build_opener()
    return _opener.open(url, data)
_opener = build_opener() 这里_opener 是一个全局变量。第一次使用时,通过build_opener() 得到一个值,以后再次使用就是保存到这个全局变量中值。
def build_opener(*handlers):
    """Create an opener object from a list of handlers.

    The opener will use several default handlers, including support
    for HTTP and FTP.

    If any of the handlers passed as arguments are subclasses of the
    default handlers, the default handlers will not be used.
    """
    import types
    def isclass(obj):
        return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")

    pener = OpenerDirector()
    default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,
                       HTTPDefaultErrorHandler, HTTPRedirectHandler,
                       FTPHandler, FileHandler, HTTPErrorProcessor]
    if hasattr(httplib, 'HTTPS'):
        default_classes.append(HTTPSHandler)
    skip = []
    for klass in default_classes:
        for check in handlers:
            if isclass(check):
                if issubclass(check, klass):
                    skip.append(klass)
            elif isinstance(check, klass):
                skip.append(klass)
    for klass in skip:
        default_classes.remove(klass)

    for klass in default_classes:
        opener.add_handler(klass())

    for h in handlers:
        if isclass(h):
            h = h()
        opener.add_handler(h)
    return opener

这 里就可以看到 默认的处理程序有 ProxyHandler, 代理服务器处理 UnknownHandler, HTTPHandler, http协议的处理 HTTPDefaultErrorHandler, HTTPRedirectHandler, http的重定向处理 FTPHandler, FTP处理 FileHandler, 文件处理 HTTPErrorProcessor

我们也可以添加自己处理程序

cookie = cookielib.CookieJar()

urllib2.HTTPCookieProcessor(cookie) 这个就是对cookie的处理程序
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

添加后就可以对每次收到响应中的Set-Cookie 记录到cookie 对象中,下次发送请求的时候就可以把这些Cookies附加到请求中
urllib2.install_opener(opener) 用我们生成的opener  替换掉urllib2中的全局变量

比如第一次请求:

connect: (www.google.cn, 80)
send: 'GET /webhp?source=g_cn HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.cn\r\nConnection: close\r\nUser-Agent: Python-urllib/2.5\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Cache-Control: private, max-age=0
header: Date: Sun, 21 Dec 2008 13:47:39 GMT
header: Expires: -1
header: Content-Type: text/html; charset=GB2312
header: Set-Cookie: PREF=ID=5d750b6ffc3d7d04:NW=1:TM=1229867259:LM=1229867259:S=XKoaKmsjYO_-CsHE; expires=Tue, 21-Dec-2010 13:47:39 GMT; path=/; domain=.google.cn
header: Server: gws
header: Transfer-Encoding: chunked
header: Connection: Close

第二次请求中就会附加

Cookie: PREF=ID=5d750b6ffc3d7d04:NW=1:TM=1229867259:LM=1229867259:S=XKoaKmsjYO_-CsHE等Cookie

connect: (www.google.cn, 80)
send: 'GET /webhp?source=g_cn HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.cn\r\nCookie: PREF=ID=5d750b6ffc3d7d04:NW=1:TM=1229867259:LM=1229867259:S=XKoaKmsjYO_-CsHE\r\nConnection: close\r\nUser-Agent: Python-urllib/2.5\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Cache-Control: private, max-age=0
header: Date: Sun, 21 Dec 2008 13:47:41 GMT
header: Expires: -1
header: Content-Type: text/html; charset=GB2312
header: Server: gws
header: Transfer-Encoding: chunked
header: Connection: Close

如果想要在urllib中启用调试,可以用

>>> import httplib
>>> httplib.HTTPConnection.debuglevel = 1           
>>> import urllib

但是在urllib2中无效,urllib2中没有发现很好的启用方法因为,

class AbstractHTTPHandler(BaseHandler):

    def __init__(self, debuglevel=0):
        self._debuglevel = debuglevel

会默认把调试级别改成0

我是这样用实现的,

cookie = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
urllib2.install_opener(opener)
opener.handle_open["http"][0].set_http_debuglevel(1)


上面转自:http://blog.163.com/hooky_2005/blog/static/5793523720101025112320100/





转自:http://hankjin.blog.163.com/blog/static/3373193720105140583594/

python访问web的利器:urllib2

使用Python访问网页主要有三种方式: urllib, urllib2, httplib
urllib比较简单,功能相对也比较弱,httplib简单强大,但好像不支持session
1. 最简单的页面访问
res=urllib2.urlopen(url)
print res.read()
2. 加上要get或post的数据
data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))
3. 加上http头
header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)

使用opener和handler
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
4. 加上session
cj = cookielib.CookieJar()
cjhandler=urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cjhandler)
urllib2.install_opener(opener)
5. 加上Basic认证
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://www.163.com/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
6. 使用代理
proxy_support = urllib2.ProxyHandler({"http":"http://1.2.3.4:3128/"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
7. 设置超时
socket.setdefaulttimeout(5)

参考:http://svn.python.org/projects/python/trunk/Doc/howto/urllib2.rst

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值