您的位置:首页 > 编程语言 > Python开发

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

2014-11-02 12:41 411 查看
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">
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: