【发布时间】:2015-09-08 17:04:44
【问题描述】:
我正在尝试读取我通过请求请求的 gzip 压缩 XML 文件。我读过的所有内容都表明解压缩应该自动发生。
#!/usr/bin/python
from __future__ import unicode_literals
import requests
if __name__ == '__main__':
url = 'http://rdf.dmoz.org/rdf/content.rdf.u8.gz'
headers = {
'Accept-Encoding': "gzip,x-gzip,deflate,sdch,compress",
'Accept-Content': 'gzip',
'HTTP-Connection': 'keep-alive',
'Accept-Language': "en-US,en;q=0.8",
}
request_reply = requests.get(url, headers=headers)
print request_reply.headers
request_reply.encoding = 'utf-8'
print request_reply.text[:200]
print request_reply.content[:200]
我的第一行输出中的标题如下所示:
{'content-length': '260071268', 'accept-ranges': 'bytes', 'keep-alive': 'timeout=5, max=100', 'server': 'Apache', 'connection': 'Keep-Alive', 'date': 'Tue, 08 Sep 2015 16:27:49 GMT', 'content-type': 'application/x-gzip'}
接下来的两行输出似乎是二进制的,我期待的是 XML 文本:
�Iɒ(�����~ؗool���u�rʹ�J���io� a2R1��ߞ|�<����_��������Ҽҿ=�Z����onnz7�{JO���}h�����6��·��>,aҚ>��hZ6�u��x���?y�_�.y�$�Բ
�Iɒ(�����~ؗool���u�rʹ�J���io� a2R1��ߞ|�<����_��������Ҽҿ=�Z����onnz7�{JO��}h�����6��·��>,aҚ>��hZ6�u��x���
我认为部分问题是site-packages/requests/packages/urllib3/response.py 无法识别 gzip,除非标头有 'content-encoding': 'gzip'
我可以通过在response.py 中的方法中添加 4 行来获得我想要的结果,如下所示:
def _init_decoder(self):
"""
Set-up the _decoder attribute if necessar.
"""
# Note: content-encoding value should be case-insensitive, per RFC 7230
# Section 3.2
content_encoding = self.headers.get('content-encoding', '').lower()
if self._decoder is None and content_encoding in self.CONTENT_DECODERS:
self._decoder = _get_decoder(content_encoding)
# My added code below this comment
return
content_type = self.headers.get('content-type', '').lower()
if self._decoder is None and content_type == 'application/x-gzip':
self._decoder = _get_decoder('gzip')
但是,有没有更好的方法?
【问题讨论】: