当使用zlib.decompress(string, wbits, bufsize)
时,请指定wbits
。示例请参见“故障排除”末尾。
故障排除
我们先来看一个curl命令,该命令下载具有未知“content-encoding”的字节范围响应(注意:我们事先知道它是某种压缩形式,可能是deflate
或gzip
):
export URL="https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-18/segments/1461860106452.21/warc/CC-MAIN-20160428161506-00007-ip-10-239-7-51.ec2.internal.warc.gz"
curl -r 266472196-266527075 $URL | gzip -dc | tee hello.txt
以下是响应头的内容:
HTTP/1.1 206 Partial Content
x-amz-id-2: IzdPq3DAPfitkgdXhEwzBSwkxwJRx9ICtfxnnruPCLSMvueRA8j7a05hKr++Na6s
x-amz-request-id: 14B89CED698E0954
Date: Sat, 06 Aug 2016 01:26:03 GMT
Last-Modified: Sat, 07 May 2016 08:39:18 GMT
ETag: "144a93586a13abf27cb9b82b10a87787"
Accept-Ranges: bytes
Content-Range: bytes 266472196-266527075/711047506
Content-Type: application/octet-stream
Content-Length: 54880
Server: AmazonS3
言归正传。
让我们显示前10个字节的十六进制输出:
curl -r 266472196-266472208 $URL | xxd
十六进制输出:
0000000: 1f8b 0800 0000 0000 0000 ecbd eb
我们可以从十六进制值中了解一些基本信息。
大致意思是它可能是一个gzip(
1f8b
),使用deflate(
0800
)而没有修改时间(
0000 0000
),或任何额外的标志(
00
),使用fat32系统(
00
)。
请参考第2.3 / 2.3.1节:
https://www.rfc-editor.org/rfc/rfc1952#section-2.3.1
现在来看Python代码:
>>> import requests
>>> url = 'https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2016-18/segments/1461860106452.21/warc/CC-MAIN-20160428161506-00006-ip-10-239-7-51.ec2.internal.warc.gz'
>>> response = requests.get(url, params={"range":"bytes=257173173-257248267"})
>>> unknown_compressed_data = response.content
注意到了什么相似之处吗?
>>> unknown_compressed_data[:10]
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00'
接下来我们随机尝试一下解压缩,参考文档:
>>> import zlib
"zlib.error:在准备解压数据时发生错误-2:流状态不一致"。
>>> zlib.decompress(unknown_compressed_data, -31)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
zlib.error: Error -2 while preparing to decompress data: inconsistent stream state
"
“解压数据时出错-3:头部校验不正确”:
"
>>> zlib.decompress(unknown_compressed_data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: incorrect header check
"zlib.error: 解压数据时出错,错误代码 -3:无效的距离太远":
>>> zlib.decompress(unknown_compressed_data, 30)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
zlib.error: Error -3 while decompressing data: invalid distance too far back
可能的解决方案:
>>> zlib.decompress(unknown_compressed_data, 31)
'WARC/1.0\r\nWARC-Type: response\r\nWARC-Date: 2016-04-28T20:14:16Z\r\nWARC-Record-ID: <urn:uu