You need to enable JavaScript to run this app. Python代理检查脚本运行时持续抛出异常的问题排查求助
优惠活动
大模型
产品
解决方案
定价
更多

Python代理检查脚本运行时持续抛出异常的问题排查求助

问题定位
  • 核心错误:变量名引用错误,遍历代理的循环变量是i,但构造请求的代理参数时使用了未定义的变量runner,直接触发NameError,这是程序一直输出error的直接原因。
  • 排查障碍:使用了无类型限制的裸except捕获,所有异常都会被统一拦截,无法输出具体报错信息,无法快速定位问题。
  • 潜在风险:拉取到的代理为IP:端口格式,requests库要求代理配置需要携带协议前缀(如http://),直接传入IP:端口会触发格式错误。
修复后的完整代码
import requests

proxies = []

body = requests.get('https://api.proxyscrape.com/v2/?request=getproxies&protocol='
                    'http&timeout=1500&country=all&ssl=all&anonymity=all').text
cut = body.split('\r\n')
cut.pop()

for i in cut:
    print('checking ', i)
    if i in proxies:
        print(i, ' is already in the pool')
    else:
        try:
            # 替换未定义的runner为循环变量i,同时补充代理协议前缀
            proxy_addr = f"http://{i}"
            res = requests.get('https://api.ipify.org?format=json',
                               proxies={'http': proxy_addr, 'https': proxy_addr}, timeout=1.5)
            if res.status_code == 200:
                print('adding ', i, ' to the pool')
                proxies.append(i)
            else:
                print(i, ' is dead')
        # 捕获具体异常并打印,方便后续排查
        except Exception as e:
            print(f"error with proxy {i}: {str(e)}")
额外优化建议
  • 可以给存储的代理也加上协议前缀,避免后续使用时还要重复处理
  • 可以增加代理校验的重试逻辑,避免网络波动导致误杀可用代理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 17:15:02