如何避免 python 中的 429 错误 requests.get()?

how to avoid 429 error requests.get() in python?

我正在尝试使用 requests.get() 从 pubg API 获取一些数据。

代码执行时,response.status_code 返回 429。

我拿到429后,200就拿不到了

如何解决这种情况?

这是我的部分代码。

for num in range(len(platform)):
   url = "https://api.pubg.com/shards/"+platform[num]+"/players/"+playerID[num]+"/seasons/"+seasonID+"/ranked"
   req = requests.get(url, headers=header)
   print(req.status_code)
[output]
200
429

根据https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429

您在 once/in 短时间内发送了太多请求。我建议使用 time.sleep(10)

import time


for num in range(len(platform)):
   ....
   ....
   time.sleep(10)

我用了 10 秒,但你必须测试它并了解需要多少时间间隔。我还建议您在计算出合适的睡眠时间后使用 https://pypi.org/project/retry/

如 sam 所述,HTTP 错误 429 表示您在特定时间内发出的请求过多。

根据 the official PUBG API documentation,API 实际上通过在每个请求中发送一个名为 X-RateLimit-Limit 的额外 header 来告诉您这些速率限制。每个请求还有一个名为 X-RateLimit-Remaining 的 header,它告诉您在第三个 header X-RateLimit-Reset 中指定的时间发生的下一次速率重置之前,您当前还有多少请求.

由于您似乎使用了请求库,因此在 python 中提出请求后,您可以通过简单的 req.headers 访问这些 header。