有问题的服务器正在给您 答复 。服务器也 很坏 ;它发送以下标头:
$ 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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"><html xmlns="http: //www.w3.org/1999/xhtml" lang="en-US">
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 3659
Content-Type: text/html
该<!DOCTYPE..>
行 。这样,过去的其余标头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))
{'<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "dtd/xhtml1-transitional.dtd"><html xmlns="http': '//www.w3.org/1999/xhtml" lang="en-US">',
'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
保留,因此可以按预期为您解码内容。