You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Requests在DigitalOcean出现Max retries超时错误求助

解决DigitalOcean环境中Python Requests连接超时问题

问题背景

以下Python Requests代码在Heroku平台运行正常,但在DigitalOcean环境中抛出连接超时错误:

headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}

def web():
  rq = requests.get("https://myurl.com/gts?search=word", headers = headers)
  print(rq)

错误信息

HTTPSConnectionPool(host='myurl.com', port=443): Max retries exceeded with url: /gts?search=word (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7fa364a89690>, 'Connection to myurl.com timed out. (connect timeout=None)'))

已尝试操作

  • 添加verify=False参数
  • 禁用控制台防火墙
  • 使用curl -I myurl.com命令访问网站

以上操作均未解决问题,以下是可行的排查和解决方向:


解决方向

1. 设置明确超时时间+重试机制

默认requests.get未设置超时,容易陷入无限等待;配合重试策略可应对网络波动:

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import requests

headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36"}

def web():
    session = requests.Session()
    # 配置重试规则:3次重试,每次间隔1秒,针对特定状态码重试
    retry = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504]
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount("https://", adapter)
    
    try:
        # 设置10秒超时(连接+读取)
        rq = session.get("https://myurl.com/gts?search=word", headers=headers, timeout=10)
        print(rq)
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")

2. 排查DigitalOcean服务器网络限制

部分目标网站会封禁云服务商IP段,可做以下检查:

  • 执行traceroute myurl.com或mtr myurl.com,查看链路是否有节点丢包/延迟过高
  • 执行nslookup myurl.com,确认服务器解析的目标域名IP与本地/Heroku环境一致
  • 更换DigitalOcean机房区域,或使用独立IP的Droplet,避免共享IP被拉黑

3. 补充完整请求头

仅设置User-Agent可能不够,模拟浏览器完整请求头:

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language": "en-US,en;q=0.5",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1"
}

def web():
    try:
        rq = requests.get("https://myurl.com/gts?search=word", headers=headers, timeout=10)
        print(rq)
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")

4. 应对目标网站反爬策略

如果目标网站有反爬机制:

  • 降低请求频率,添加随机间隔(如time.sleep(random.uniform(1,3)))
  • 使用代理IP规避IP封禁(选择高匿代理,避免代理IP本身被拉黑)

内容的提问来源于stack exchange,提问作者Emir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 06:06:45