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

求助:使用Requests库请求URL超时,浏览器却可正常访问

问题描述

之前可正常运行的代码,现在执行时出现连接超时错误。原以为目标URL发生了变更,但将该URL粘贴至浏览器可获得成功响应。然而在终端使用curl命令或PyCharm中运行代码时,均会触发超时错误。已尝试设置请求头与重试机制,但使用Requests库仍无法获取成功响应。

代码示例

import requests

# 创建会话对象
session = requests.Session()

# 添加请求头(模拟浏览器User-Agent)
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.3 Safari/605.1.15'
}

# 发送POST请求
response = session.post('https://www.valueinvestorsclub.com/ideas/loadideas', headers=headers)

# 打印响应
print(response)

报错信息

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.valueinvestorsclub.com', port=443): Max retries exceeded with url: /ideas/loadideas (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x122309b80>: Failed to establish a new connection: [Errno 60] Operation timed out'))
解决方向
  • 检查网络代理/环境差异:浏览器可能自动使用了系统代理、VPN或浏览器专属代理,但终端和PyCharm未配置对应代理。可以手动给Requests添加代理:

    proxies = {
        'http': 'http://你的代理地址:端口',
        'https': 'https://你的代理地址:端口'
    }
    response = session.post('https://www.valueinvestorsclub.com/ideas/loadideas', headers=headers, proxies=proxies)
    

    也可以用ping www.valueinvestorsclub.com或traceroute www.valueinvestorsclub.com排查终端到目标域名的网络链路是否通畅。

  • 补充完整请求参数:浏览器发送POST请求时,可能携带了Cookie、表单数据或其他请求头字段(比如Referer),而你的代码仅模拟了User-Agent。打开浏览器开发者工具(F12),找到该POST请求,复制完整的请求头和Form Data,补充到代码中:

    # 从开发者工具复制的表单参数
    payload = {
        'page': '1',
        'sort': 'newest'
    }
    # 从浏览器复制的Cookie
    headers['Cookie'] = '浏览器中复制的Cookie内容'
    # 添加Referer头
    headers['Referer'] = 'https://www.valueinvestorsclub.com/ideas'
    
    response = session.post('https://www.valueinvestorsclub.com/ideas/loadideas', headers=headers, data=payload)
    
  • 调整超时与重试策略:默认超时时间可能过短,或重试机制未正确生效。显式设置超时时间,并配置更合理的重试策略:

    from requests.adapters import HTTPAdapter
    from urllib3.util.retry import Retry
    
    # 配置重试策略
    retry_strategy = Retry(
        total=3,  # 总重试次数
        backoff_factor=1,  # 重试间隔递增因子
        status_forcelist=[429, 500, 502, 503, 504]  # 需要重试的状态码
    )
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount('https://', adapter)
    
    # 设置10秒超时
    response = session.post('https://www.valueinvestorsclub.com/ideas/loadideas', headers=headers, timeout=10)
    
  • 验证TLS版本兼容性:部分网站仅支持特定TLS版本,Requests默认的TLS版本可能不匹配。可以强制指定TLS版本:

    import ssl
    from requests.adapters import HTTPAdapter
    from urllib3.poolmanager import PoolManager
    
    class TLSAdapter(HTTPAdapter):
        def init_poolmanager(self, *args, **kwargs):
            kwargs['ssl_version'] = ssl.PROTOCOL_TLSv1_2
            return super().init_poolmanager(*args, **kwargs)
    
    session.mount('https://', TLSAdapter())
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:52:41