首页 > 解决方案 > 使用 Python requests 包时如何避免很多请求被拒绝?

问题描述

我使用 requests 包从网站获取一些地震目录:ISC 地震公告

当内容表很小时,一切都很好。但是当涉及到海量搜索或循环搜索时,我设置了不同的参数来循环运行请求。它将不返回任何可用数据:

抱歉,目前无法处理您的请求。请在几分钟后再试一次。

谁能告诉我如何避免太多被拒绝的请求?

这是我的脚本:

# import package
import requests
Url = ‘http://www.isc.ac.uk/cgi-bin/web-db-v4?iscreview=on&out_format=CSV&ttime=on&ttres=on&tdef=on&amps=on&phaselist=&stnsearch=STN&sta_list=CLC&stn_ctr_lat=&stn_ctr_lon=&stn_radius=&max_stn_dist_units=deg&stn_top_lat=&stn_bot_lat=&stn_left_lon=&stn_right_lon=&stn_srn=&stn_grn=&bot_lat=&top_lat=&left_lon=&right_lon=&ctr_lat=&ctr_lon=&radius=&max_dist_units=deg&searchshape=GLOBAL&srn=&grn=&start_year=2009&start_month=7&start_day=01&start_time=00%3A00%3A00&end_year=2019&end_month=8&end_day=01&end_time=00%3A00%3A00&min_dep=&max_dep=&min_mag=6.0&max_mag=6.9&req_mag_type=Any&req_mag_agcy=Any&include_links=on&request=STNARRIVALS’

R.requests(URL)

print(R.text)

标签: pythonpython-requests

解决方案


使用HTTPAdapter的Retry机制,在发生临时故障时自动重新发送请求。您可能感兴趣的一些设置:

  1. total- 允许的重试总数。如果在没有成功响应的情况下达到限制,则该请求被视为失败。
  2. backoff_factor- 由于失败的请求通常发生在服务器加载时,因此在重试之间设置延迟以便服务器可以呼吸是有益的。把它想象成第一个请求将在第 1 秒发生,第 2 个请求在第 2 秒发生,第 3 个请求在第 4 秒发生,第 4 个请求在第 8 秒发生,第 5 个请求在第 16 秒发生,依此类推直到配置好BACKOFF_MAX
  3. allowed_methods- 您要重试的 HTTP 方法。
  4. status_forcelist- 应重试的 HTTP 状态代码。通常,这是 5xx 系列,因为这些是源自服务器的错误,如果重试可能会成功。
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

retry_strategy = Retry(
    total=5,
    backoff_factor=0.1,
    allowed_methods=["GET"],
    status_forcelist=[500, 502, 504],
)
adapter = HTTPAdapter(max_retries=retry_strategy)
http = requests.Session()
http.mount("https://", adapter)
http.mount("http://", adapter)

response = http.get("https://google.com")
print(response.status_code)

在此示例中,如果响应失败,我们可以确定一系列 5 次重试在时间上相隔 0.1 倍,但仍然失败。但是,如果服务器故障不是持续存在的,那么由于重试次数随着时间的推移而分开,这很可能会成功。


推荐阅读