python urllib2 处理编码的两个注意点

 urllib2可以抓取网页,为了模拟浏览器需要增加如下header:

  Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:zh,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Host:www.baidu.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36


把header作为一个dict传参数,但是由于请求gzip,所以需要对返回结果进行解压,或者就不进行http gzip请求

   from StringIO import StringIO

   import gzip    
    req  = urllib2.Request(url, headers=headers)
    resp = urllib2.urlopen(req)

        content = ''
        # handle gzip compress
       # 这里需要注意,因为模拟chrome的请求,所以返回的是gzip格式的编码,而urllib2是不会自动处理编码的,需要用StringIO和gzip来协助处理,得到解压后的串
       #否则会报错:UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: invalid start byte
        if resp.info().get('Content-Encoding') == 'gzip':
            buf = StringIO(resp.read())
            f = gzip.GzipFile(fileobj=buf)
            content = f.read()
        else :
            content = resp.read()
       
       # 这里根据网页返回的实际charset进行unicode编码
        encoding = resp.headers['content-type'].split('charset=')[-1]
        ucontent = unicode(content, encoding)
</pre><pre code_snippet_id="505001" snippet_file_name="blog_20141102_8_3978368" name="code" class="python">参考:
http://stackoverflow.com/questions/3947120/does-python-urllib2-automatically-uncompress-gzip-data-fetched-from-webpage
</pre><pre code_snippet_id="505001" snippet_file_name="blog_20141102_11_1775350" name="code" class="python">

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值