解码 urllib.request 响应

Decoding urllib.request response

我打开此 url 时收到此回复:

r = Request(r'http://airdates.tv/')
h = urlopen(r).readline()
print(h)

回复:

b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00\xed\xbdkv\xdbH\x96.\xfa\xbbj\x14Q\xaeuJ\xce\xee4E\x82\xa4(9m\xe7\xd2\xd3VZ\xaf2e\xab2k\xf5\xc2\n'

这是什么编码? 有没有办法基于标准库解码?
预先感谢您对此事的任何见解!

PS: 好像是gzip

如您所料,它是 gzip 压缩的 HTML。

与其使用 urllib,不如使用 requests,这将为您解压缩响应:

import requests

r = requests.get('http://airdates.tv/')
print(r.text)

您可以使用 pip install requests 安装它,永远不会回头。


如果你真的必须限制自己使用标准库,那么用 gzip 模块解压它:

import gzip
import urllib2
from cStringIO import StringIO

f = urllib2.urlopen('http://airdates.tv/')

# how to determine the content encoding
content_encoding = f.headers.get('Content-Encoding')
#print(content_encoding)

# how to decompress gzip data with Python 3
if content_encoding == 'gzip':
    response = gzip.decompress(f.read())

# decompress with Python 2
if content_encoding == 'gzip':   
    gz = gzip.GzipFile(fileobj=StringIO(f.read())
    response = gz.read()

mhawke 的解决方案(使用 requests 而不是 urllib)工作完美,在大多数情况下应该是首选。 也就是说,我一直在寻找不需要安装第 3 方库的解决方案(因此我选择 urllib 而不是 requests)。

我找到了一个使用标准库的解决方案:

import zlib
from urllib.request import Request, urlopen

r = Request(r'http://airdates.tv/')
h = urlopen(r).read()
decomp_gzip = zlib.decompress(h, 16+zlib.MAX_WBITS)
print(decomp_gzip)

这会产生以下响应:

b'<!DOCTYPE html>\n (continues...)'