使用类似的压缩gzip
已变得非常流行(约73%的网站都在使用它,包括Google,YouTube,Yahoo,Wikipedia,Reddit,Stack Overflow
和Stack Exchange Network
网站等大型网站)。 如果你像原始答案中那样使用gzip
压缩响应进行简单解码,则会收到类似以下错误:
UnicodeDecodeError:'utf8'
编解码器无法解码位置1的字节0x8b
为了解码gzpipped响应,你需要添加以下模块(在Python 3中):
import gzip
import io
然后,你可以像这样解析内容:
response = urlopen("https://example.com/gzipped-ressource")
buffer = io.BytesIO(response.read()) # Use StringIO.StringIO(response.read()) in Python 2
gzipped_file = gzip.GzipFile(fileobj=buffer)
decoded = gzipped_file.read()
content = decoded.decode("utf-8") # Replace utf-8 with the source encoding of your requested resource
此代码读取响应,并将字节放入缓冲区。然后,gzip模块使用GZipFile函数读取缓冲区。之后,可以将压缩后的文件再次读取为字节,最后将其解码为通常可读的文本。