urllib2.urlopen处理gzip数据

urllib2.urlopen处理gzip数据 | yanghao's blog

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 urllib2. Bookmark the permalink.

发表评论

原文地址:https://www.cnblogs.com/lexus/p/2405385.html