小编典典
有问题的服务器正在给您 答复 。服务器也 很坏 ;它发送以下标头:
$ curl -D - -o /dev/null -s -H 'Accept-Encoding: gzip, deflate' http://www.wrcc.dri.edu/WRCCWrappers.py?sodxtrmts+028815+por+por+pcpn+none+mave+5+01+F
HTTP/1.1 200 OK
Date: Tue, 06 Jan 2015 17:46:49 GMT
Server: Apache
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 3659
Content-Type: text/html
该.>行 没有有效的HTTP标头 。这样,过去的其余标头Server将 被忽略
。为什么服务器插入的原因尚不清楚;在所有可能的情况下,WRCCWrappers.py都是CGI脚本,它不输出标头,但在doctype行之后确实包含一个双换行符,将Apache服务器复制到其中插入其他标头中。
因此,requests也不会检测到数据是gzip编码的。数据就在那里,您只需要解码即可。或者,如果不是很不完整,也可以。
解决方法是告诉服务器不要打扰压缩:
headers = {'Accept-Encoding': 'identity'}
r = requests.get(url, headers=headers)
并返回未压缩的响应。
顺便说一下,在Python 2上,HTTP标头解析器不是那么严格,它设法将doctype声明为标头:
>>> pprint(dict(r.headers))
{'',
'connection': 'Keep-Alive',
'content-encoding': 'gzip',
'content-length': '3659',
'content-type': 'text/html',
'date': 'Tue, 06 Jan 2015 17:42:06 GMT',
'keep-alive': 'timeout=5, max=100',
'server': 'Apache',
'vary': 'Accept-Encoding'}
并且content-encoding信息得以requests保留,因此可以按预期为您解码内容。
2020-12-20