Pythonの3のgzipで圧縮されたサーバの応答を解凍するための最良の方法は何ですか?
-
23-08-2019 - |
質問
私は仕事にこれを期待していた。
>>> 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とZLIBが同じ圧縮されているが、異なるヘッダ/「ラッピング」と。あなたのエラーメッセージにこの情報を持っている)gzip
と正常に動作します。
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()
他のヒント
は、Python 3では、 StringIO
のですio
モジュール内のクラスます。
あなたが変更した場合は、リンクに例えばだからます:
import StringIO
compressedstream = StringIO.StringIO(compresseddata)
と
import io
compressedstream = io.StringIO(compresseddata)
それは動作するはずます。
はPython 3.2以降を使用して、誰のために、ここでの回答のいずれよりも応答を解凍するためにさらに簡単な方法があります:
import gzip
import urllib.request
request = urllib.request.Request(
"http://example.com/",
headers={"Accept-Encoding": "gzip"})
response = urllib.request.urlopen(request)
result = gzip.decompress(response.read())
所属していません StackOverflow