【问题标题】:Python requests GET takes a long time to respond to some requestsPython请求GET需要很长时间才能响应一些请求
【发布时间】:2016-11-07 23:34:23
【问题描述】:

我正在使用Python requestsget方法查询MediaWiki API,但是收到响应需要很多时间。相同的请求通过 Web 浏览器非常快地收到响应。我在请求 google.com 时遇到了同样的问题。以下是我在 Windows 10 上的 Python 3.5 中尝试的示例代码:

response = requests.get("https://www.google.com")
response = requests.get("https://en.wikipedia.org/wiki/Main_Page")
response = requests.get("http://en.wikipedia.org/w/api.php?", params={'action':'query', 'format':'json', 'titles':'Labor_mobility'})

但是,我在检索其他网站时不会遇到这个问题,例如:

response = requests.get("http://www.stackoverflow.com")
response = requests.get("https://www.python.org/")

【问题讨论】:

  • 回复需要多长时间?
  • Python 请求也不正式支持 python 3.5
  • 您是否尝试在网址后添加stream=True?例如:requests.get("https://www.google.com", stream=True)
  • @NendoTaka,感谢您的回复。通常它们需要不到 0.5 秒,但是对于我现在面临的问题,它们每个都需要大约 22 秒!另外,我尝试了 Python 2.7,但我遇到了同样的问题。我也试过 requests.get("google.com", stream=True)。它没有改变任何东西。
  • 同样的问题,对我有用:unix.stackexchange.com/questions/500286/…

标签: python performance get python-requests python-3.5


【解决方案1】:

这听起来像是与服务器的底层连接存在问题,因为对其他 URL 的请求有效。想到这些:

  • 服务器可能只允许特定的用户代理字符串

尝试添加无害的标头,例如:requests.get("https://www.example.com", headers={"User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36"})

  • 服务器会限制您

等待几分钟,然后重试。如果这解决了您的问题,您可以通过添加 time.sleep() 来减慢您的代码速度,以防止再次受到速率限制。

  • IPv6 不起作用,但 IPv4 起作用

通过执行curl --ipv6 -v https://www.example.com 进行验证。然后,与curl --ipv4 -v https://www.example.com 进行比较。如果后者明显更快,则您的 IPv6 连接可能有问题。检查here 以获取可能的解决方案。

没有解决您的问题?

如果那没有解决您的问题,我收集了一些其他可能的解决方案here

【讨论】:

  • 设置标题在我的情况下有效。谢谢@vauhochzett
  • @vauhochzett,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2018-07-31
  • 2018-01-15
  • 1970-01-01
  • 2018-04-06
相关资源
最近更新 更多