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
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">
相关文章推荐
- python 处理中文需要注意的编码问题
- 【转】Python urllib2.urlopen打开中文url的编码处理
- python urllib中的编码处理示例
- Python urllib2.urlopen打开中文url的编码处理_Luffy's Space_百度空间
- python urllib2处理重定向的问题
- python写的sogou代理全网加速器两个注意的
- python中文字符串编码处理
- 学习python处理python编码问题
- 在VB.NET中处理构造函数时值得注意的两个陈述
- Python编码时应该注意的一些事情
- Python学习:时间处理工具--dateutil两个简单用法
- 中文编码相关,python处理gbk编码的xml文件方法
- python处理字符串编码
- 利用python处理xml -- 中文编码问题
- Python 编码时应该注意的几件事情
- 转载 - Python编码时的注意事项
- 在VB.NET中处理构造函数时值得注意的两个陈述
- 对请求统一设置编码来处理中文乱码时的注意事项
- [Python学习]Unicode及编码处理心得
- MySQL处理空值时你需要注意的两个问题