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

Selenium代理配置报错求助:爬取猫眼电影时IP被封,代理连接失败

修复Selenium配置代理时的net::ERR_PROXY_CONNECTION_FAILED错误

核心问题分析

报错net::ERR_PROXY_CONNECTION_FAILED本质是代理服务器无法建立连接,常见原因包括代理格式错误、代理失效、Chrome配置缺失、Driver路径错误。

具体修复步骤

  • 验证代理有效性与格式
    确保ipaddress.txt中的代理是IP:端口的完整格式(如111.222.333.444:8080),无多余换行或空格。先手动测试代理:在Chrome浏览器设置中添加该代理,访问http://httpbin.org/ip,确认能正常返回IP信息,排除代理本身失效的问题。

  • 修正ChromeDriver路径
    代码中driver_path = r'\chromedriver.exe'是根目录路径,系统大概率无法找到文件。改为绝对路径(如r'C:\tools\chromedriver.exe'),若chromedriver与脚本同目录,直接写'chromedriver.exe'即可。

  • 完善无头模式配置
    仅使用--headless参数可能导致代理连接异常,补充必要参数避免环境检测与连接问题:

    chrome_options.add_argument('--headless=new')  # 新版无头模式,兼容性更好
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--ignore-certificate-errors')  # 忽略代理证书错误
    
  • 添加异常处理与资源释放
    循环中未处理异常会导致Driver进程残留,且后续代理测试中断。用try-except-finally确保每次测试后关闭Driver:

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import WebDriverException

with open('ipaddress.txt', 'r') as f:
    iplist = f.readlines()
    for i in iplist:
        ip = i.strip()  # 直接strip()去除所有空白字符(换行、空格)
        driver_path = 'chromedriver.exe'  # 改为实际路径
        service = Service(driver_path)
        chrome_options = Options()
        
        # 完善无头模式与代理相关配置
        chrome_options.add_argument('--headless=new')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_argument(f'--proxy-server=http://{ip}')
        
        driver = None
        try:
            driver = webdriver.Chrome(service=service, options=chrome_options)
            driver.get('http://httpbin.org/ip')
            if 'origin' in driver.page_source:
                print(f"可用代理: {ip}")
        except WebDriverException as e:
            print(f"代理 {ip} 连接失败: {str(e)}")
        finally:
            if driver:
                driver.quit()  # 彻底关闭Driver进程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:12:34