Python 3에서 Gzip'ed 서버 응답을 압축하는 가장 좋은 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/720273

  •  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

그러나 그렇지 않습니다. 파이썬으로 뛰어 들었습니다 Stringio를 사용합니다 이 예에서는 파이썬 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()

다른 팁

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())
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top