有问题的服务器正在给你一个压缩响应。服务器也是非常破碎;它发送以下标头:
$ 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
The <!DOCTYPE..>
线有不是有效的 HTTP 标头。因此,剩余的标头过去了Server
are ignored。尚不清楚服务器为何会插话;在所有可能的情况下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'}
and the content-encoding
信息得以保存,所以有requests
如预期的那样为您解码内容。