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

Python Requests使用代理访问HTTPS页面失效问题求助

代理测试代码问题排查与修正

代码核心问题分析

你的代码逻辑框架没问题,但几个细节会导致测试结果不准,甚至直接失败:

  1. 异常捕获范围过窄:IOError覆盖不了requests抛出的大部分异常,比如代理连接失败、SSL错误、超时这些都不属于IOError,会导致未捕获异常中断程序,或者你误以为是代理失效但其实是其他问题。
  2. HTTPS代理配置错误:绝大多数支持HTTPS的代理,只需要用HTTP协议连接代理服务器(通过HTTP隧道处理HTTPS请求),不需要写成https://ip:port,这样写反而会导致连接失败。
  3. 未验证响应状态:就算请求没抛异常,也可能返回403、500这类错误状态码,不能直接判定代理可用。

修正后的测试代码

import requests

def proxy_json_test_saved_proxies(self):
    test_count = 1
    timeout_seconds = 10
    working_http = 0
    working_https = 0
    for proxy_dict in self.all_proxies:
        print("#######")
        print(f"Testing proxy {test_count}/{len(self.all_proxies)}")
        test_count += 1
        # 修正HTTPS代理的协议,用HTTP连接代理处理HTTPS请求
        proxy = {
            'http': f'http://{proxy_dict["address"]}',
            'https': f'http://{proxy_dict["address"]}'
        }
        print(proxy)
        
        print("Try http connection:")
        try:
            resp = requests.get("http://example.com", proxies=proxy, timeout=timeout_seconds)
            resp.raise_for_status()  # 确保响应状态码为2xx
            print("Success")
            working_http += 1
        except requests.exceptions.RequestException as e:
            # 打印具体错误信息,方便排查
            print(f"Fail: {str(e)}")
        
        print("Try https connection:")
        try:
            resp = requests.get("https://example.com", proxies=proxy, timeout=timeout_seconds)
            resp.raise_for_status()
            print("Success")
            working_https += 1
        except requests.exceptions.RequestException as e:
            print(f"Fail: {str(e)}")
        
        print(f"Working http: {working_http}")
        print(f"Working https: {working_https}")

额外排查方向

  • 免费代理时效性极差:你手动验证时可用,但代码测试时可能已经被封禁、占用或失效,尤其是80、8080这类通用端口的代理,存活时间通常只有几分钟甚至更短。
  • 代理可能需要身份验证:部分免费代理会隐藏登录要求,在线验证工具可能自动处理了,但代码里需要显式添加,格式为http://用户名:密码@ip:port。
  • 本地网络限制:你的运营商或公司网络可能屏蔽了免费代理的IP段,或者拦截了代理请求,可以换个网络(比如手机热点)测试。
  • 代理地区限制:有些代理只允许访问特定地区的网站,example.com可能不在允许列表里,可以换成目标爬取站点的域名测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:01:47