urllib2.urlopen处理gzip数据

某些网站不管的请求头部带不带

Accept-Encoding:gzip

他都返回gzip压缩过的内容,也就是返回的头部都带有

Content-Encoding:gzip

对于这种网站在使用urllib2.urlopen获取数据时候由于urlopen不会自动处理gzip,得到的都是乱码,让人难以看懂的内容

对付这种情况就需要我们单独处理

f = urllib2.urlopen(url)
headers = f.info()
rawdata = f.read()
if ('Content-Encoding' in headers and headers['Content-Encoding']) or \
    ('content-encoding' in headers and headers['content-encoding']):
    import gzip
    import StringIO
    data = StringIO.StringIO(rawdata)
    gz = gzip.GzipFile(fileobj=data)
    rawdata = gz.read()
    gz.close()
This entry was posted in Python and tagged . Bookmark the permalink.

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>