python urllib2 (转)

上一篇 / 下一篇  2009-10-31 16:53:24 / 个人分类:python

当处理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)

TAG:

 

评分:0

我来说两句

Open Toolbar