我原以为这会起作用:
>>> import urllib.request as r
>>> import zlib
>>> r.urlopen( r.Request("http://google.com/search?q=foo", headers={"User-Agent": "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11", "Accept-Encoding": "gzip"}) ).read()
b'af0\r\n\x1f\x8b\x08...(long binary string)'
>>> zlib.decompress(_)
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
zlib.decompress(x)
zlib.error: Error -3 while decompressing data: incorrect header check
但事实并非如此。深入Python使用 StringIO在这个例子中,但这似乎在Python 3中缺失了。正确的做法是什么?
它可以很好地与gzip
(gzip 和 zlib 是相同的压缩,但具有不同的标头/“包装”。您的错误消息中包含此信息)。
import gzip
import urllib.request
request = urllib.request.Request(
"http://google.com/search?q=foo",
headers={
"Accept-Encoding": "gzip",
"User-Agent": "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11",
})
response = urllib.request.urlopen(request)
gzipFile = gzip.GzipFile(fileobj=response)
gzipFile.read()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)