【问题标题】:Unable to read requests HTML response from a URL无法从 URL 读取请求 HTML 响应
【发布时间】:2018-12-03 11:27:45
【问题描述】:

我正在使用 python 请求库来发出 http 请求。对于这个网站:https://www.epi.org/resources/budget/ 我无法阅读 HTML 响应,因为它不是人类可读的,看起来它受 cloudfare ddos​​ 保护。下面是我的简单代码。

import requests

headers = {'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
           'accept-encoding': 'gzip, deflate, br',
           'accept-language': 'en-US,en;q=0.9,pt;q=0.8',
           'cache-control': 'max-age=0',
           'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
           'upgrade-insecure-requests': '1'}

s = requests.Session()
a = s.get('https://www.epi.org/resources/budget/',headers=headers)
print (a.text)

响应 HTML 如下所示:https://justpaste.it/6ie73

【问题讨论】:

    标签: python-3.x session cookies python-requests ddos


    【解决方案1】:

    获得不可读内容的原因是Accept-Encoding。与浏览器不同,如果 Python 得到gzip 响应,我们必须自己解包。 br 也需要这样做,但使用不同的模块 brotl 。所以你应该设置'Accept-Encoding': 'default'。顺便说一句,如果您需要完整的内容,则必须进行渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 2021-05-14
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      相关资源
      最近更新 更多