2009-04-06 32 views
7

tôi đã mong đợi này để làm việc:Cách tốt nhất để giải nén đáp ứng máy chủ gzip'ed bằng Python 3 là gì?

>>> 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 

Nhưng nó không. Lặn sâu vào Python uses StringIO trong ví dụ này, nhưng điều đó dường như bị thiếu từ Python 3. Cách làm đúng đắn là gì?

Trả lời

17

Nó hoạt động tốt với gzip (gzip và zlib là cùng một nén nhưng với các tiêu đề khác nhau/"gói". Lỗi của bạn có thông tin này trong thư).

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() 
4

Trong Python 3, StringIO là một lớp trong mô-đun io.

Vì vậy, ví dụ như bạn liên kết đến, nếu bạn thay đổi:

import StringIO 
compressedstream = StringIO.StringIO(compresseddata) 

tới:

import io 
compressedstream = io.StringIO(compresseddata) 

nó nên làm việc.

2

Đối với bất cứ ai sử dụng Python 3.2 hoặc mới hơn, có một cách đơn giản hơn để giải nén một phản ứng hơn bất kỳ các câu trả lời ở đây:

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()) 
Các vấn đề liên quan