您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python请求获取HTML?

使用Python请求获取HTML?

有问题的服务器正在给您 答复 。服务器也 很坏 ;它发送以下标头:

$ 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保留,因此可以按预期为您解码内容

python 2022/1/1 18:27:39 有184人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶