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

在Amazon EC2实例使用Selenium Wire Chrome时频繁遇NewConnectionError

问题描述

在Amazon EC2实例上使用Selenium Wire Chrome时,频繁出现以下非必现错误:

HTTPConnectionPool(host='localhost', port=32817): Max retries exceeded with url: /session/286f9b1508aa3fab78fee8a606577194/execute/sync (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd56e845400>: Failed to establish a new connection: [Errno 111] Connection refused'))

重新发送请求有时能正常工作,但后续请求仍可能失败。

使用的Chrome配置选项:

proxies: dict = {
    "httpProxy": proxy_string
}
options.proxy = Proxy(proxies)

# Other Chrome options
options.add_argument("--no-sandbox")
options.add_argument("--headless")
options.add_argument('--ignore-certificate-errors')
options.add_argument("--disable-gpu")
options.add_argument("--disable-software-rasterizer")
options.add_argument("--incognito")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--window-size=1920,1080")
options.add_argument("--start-maximized")
options.add_argument("--disable-popup-blocking")
options.add_argument("--disable-extensions")
options.add_argument("--no-zygote")
options.add_argument("--disable-notifications")

Chrome版本为126.0.6478.55,Docker中安装Chrome和驱动的步骤:

RUN apt-get update && apt-get install -y wget gnupg2 curl unzip \
    && wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list \
    && apt-get update \
    && apt-get install -y google-chrome-stable

# Check Chrome installation
RUN echo google-chrome --version
RUN google-chrome --version | awk '{print $3}' > /tmp/chrome_version.txt

RUN wget -N "https://storage.googleapis.com/chrome-for-testing-public/126.0.6478.55/linux64/chromedriver-linux64.zip" -P /tmp

RUN unzip /tmp/chromedriver-linux64.zip -d /tmp
RUN mv /tmp/chromedriver-linux64/chromedriver /usr/local/bin/chromedriver \
   && chmod 0755 /usr/local/bin/chromedriver \
   && rm -rf /tmp/chromedriver-linux64.zip

另外编写了以下检查实例有效性的方法,询问是否会导致上述问题:

@staticmethod
def is_instance_valid(instance):
    try:
        instance.execute_script("return true;")
        logging.info("Browser instance is valid")
        return True
    except WebDriverException:
        logging.error("Browser instance is invalid")
        return False

问题分析与解决方案

1. 核心原因判断

这个错误本质是Selenium无法连接到ChromeDriver的会话端口,大概率是Chrome实例意外崩溃/端口被系统回收,或是Selenium Wire代理与Chrome代理配置冲突,也可能是EC2资源不足导致进程被系统强制终止。

2. 检查方法的影响

你写的is_instance_valid方法本身不会引发问题,但要注意:

  • 如果在实例已经不稳定的情况下频繁调用execute_script,可能加速连接资源耗尽,但这不是问题根源
  • 该方法仅能做简单的存活检查,无法覆盖Chrome进程假死、端口异常的情况

3. 针对性修复建议

(1)解决Selenium Wire代理冲突

Selenium Wire本身会启动本地代理拦截请求,配置外部代理时需使用Selenium Wire专属方式,而非直接给ChromeOptions设置代理:

# 替换原有的proxy配置
wire_options = {
    'proxy': {
        'http': proxy_string,
        'https': proxy_string,
        'no_proxy': 'localhost,127.0.0.1'  # 排除本地Selenium Wire代理地址,避免循环代理
    }
}

# 初始化driver时传入wire_options
driver = webdriver.Chrome(options=options, seleniumwire_options=wire_options)

(2)优化Chrome启动参数

  • 移除冲突参数:--start-maximized和--window-size=1920,1080功能重复,保留其一即可
  • 增加进程稳定性参数:
    options.add_argument("--disable-background-networking")
    options.add_argument("--disable-background-timer-throttling")
    options.add_argument("--disable-backgrounding-occluded-windows")
    options.add_argument("--disable-renderer-backgrounding")
    
  • --no-zygote在无沙箱环境下可能导致进程管理异常,建议测试移除该参数

(3)EC2资源与进程管理

  • 检查EC2实例的CPU、内存使用率,Chrome在headless模式下仍会占用较多资源,资源不足会触发系统OOM killer终止进程
  • 确保每次使用完driver后调用driver.quit()彻底销毁进程,避免端口和资源泄漏
  • 增加会话超时重试机制,捕获到连接拒绝错误时自动重新初始化driver:
    def get_driver():
        max_retries = 3
        for _ in range(max_retries):
            try:
                # 这里放你的driver初始化逻辑
                driver = webdriver.Chrome(options=options, seleniumwire_options=wire_options)
                return driver
            except (WebDriverException, ConnectionRefusedError):
                # 尝试销毁残留进程
                try:
                    driver.quit()
                except:
                    pass
                time.sleep(2)
        raise Exception("多次重试后仍无法初始化driver")
    

(4)确认Chrome与ChromeDriver版本严格匹配

你的Dockerfile中手动指定了ChromeDriver版本,但google-chrome-stable默认安装最新版,可能出现版本不匹配。修改Dockerfile强制安装指定版本:

# 替换原有的apt-get install命令,指定对应版本
RUN apt-get install -y google-chrome-stable=126.0.6478.55-1

4. 验证步骤

  1. 先移除--no-zygote参数,测试是否还出现连接拒绝错误
  2. 改用Selenium Wire的代理配置方式,替换原有的ChromeOptions proxy设置
  3. 监控EC2资源使用情况,查看/var/log/syslog或dmesg日志,确认是否有OOM(内存不足)记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:50:54