gpt4 book ai didi

python - 这个 gzip 格式有什么问题?

转载 作者:可可西里 更新时间:2023-11-01 16:02:46 25 4
gpt4 key购买 nike

我使用以下 python 代码通过 gzip 压缩从服务器下载网页:

url = "http://www.v-gn.de/wbb/"
import urllib2
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
content = response.read()
response.close()

import gzip
from StringIO import StringIO
html = gzip.GzipFile(fileobj=StringIO(content)).read()

这通常有效,但对于指定的 URL 会失败并出现 struct.error 异常。如果我将 wget 与“Accept-encoding” header 一起使用,我会得到类似的结果。然而,浏览器似乎能够解压缩响应。

所以我的问题是:有没有办法让我的 python 代码解压缩 HTTP 响应,而无需通过删除“Accept-encoding” header 来禁用压缩?

为了完整起见,这是我用于 wget 的行:

wget --user-agent="Mozilla" --header="Accept-Encoding: gzip,deflate" http://www.v-gn.de/wbb/

最佳答案

看来您可以在 gzip.GzipFile 对象上调用 readline(),但是read() 引发了一个 struct.error 因为文件突然结束。

因为 readline 有效(除了最后),你可以这样做:

import urllib2
import StringIO
import gzip
import struct

url = "http://www.v-gn.de/wbb/"
request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
content = response.read()
response.close()
fh=StringIO.StringIO(content)
html = gzip.GzipFile(fileobj=StringIO.StringIO(content))
try:
for line in html:
line=line.rstrip()
print(line)
except struct.error:
pass

关于python - 这个 gzip 格式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3652177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com