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

Windows下Selenium ChromeDriver出现[WinError 10061]连接拒绝错误求助

Windows 10下Selenium ChromeDriver连接被拒绝(连接随机端口而非8080)

此前在Windows 10上用Python+Chrome WebDriver运行Selenium测试完全正常,现在突然出现ConnectionRefusedError,每次尝试连接的是随机端口(不是目标站点的8080)。

环境信息

  • Windows 10
  • PyCharm 2023
  • Chrome浏览器版本:126
  • ChromeDriver版本:126
  • ChromeDriver已添加至系统PATH
  • Python 3.10
  • Selenium 4.22.0

测试代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)

# 配置无头模式选项
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920x1080")

# 初始化WebDriver
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)

# 打开目标页面
driver.get("http://localhost:8080/")

# 测试1:检查Logo是否存在
def test_logo_presence():
    try:
        # 延长等待时间至20秒
        logo = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, "#logo a"))
        )
        assert logo is not None, "Logo不存在"
        print("测试1:Logo存在")
    except Exception as e:
        print(f"发生错误:{e}")
    finally:
        driver.quit()

# 执行测试
test_logo_presence()

错误信息

if new_retry.is_exhausted():
    reason = error or ResponseError(cause)
>   raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=12328): Max retries exceeded with url: /session/2fae43639c8c634131a5b00a2c7f331f/element (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001D75F93EB90>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。'))

已尝试的解决步骤

  • 确认localhost:8080可正常访问,页面能正常打开
  • 尝试延长WebDriver等待时长
  • 确保Chrome和ChromeDriver均为最新版本(126)
  • 检查ChromeDriver已正确添加至系统PATH
  • 验证元素#logo a在DevTools中存在且可访问
  • 使用pytest运行另一脚本可正常工作(脚本如下):
# test_opencart.py
# 该脚本有对应的conftest配置,此处省略

import pytest

@pytest.mark.parametrize("browser_name", ["chrome", "firefox", "ie"])
def test_opencart_homepage(browser_name, browser, base_url):
    browser.get(base_url)
    assert "Your Store" in browser.title, "页面标题未显示当前处于Opencart首页"

@pytest.fixture
def browser_name(request):
    return request.param

解决建议

  1. 清理残留Chrome进程
    打开任务管理器,结束所有chrome.exe和chromedriver.exe进程后重新运行测试。无头模式下Chrome后台进程可能未正常退出,导致端口占用或通信异常。

  2. 添加Chrome权限参数
    在ChromeOptions中追加以下参数,解决无头模式下的权限或资源限制问题:

    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    
  3. 指定ChromeDriver固定端口
    初始化Service时指定默认端口9515,避免随机端口冲突:

    service = ChromeService(executable_path=ChromeDriverManager().install(), port=9515)
    

    提前确认9515端口未被其他程序占用。

  4. 输出Driver日志排查细节
    给ChromeService添加日志路径,查看Driver与浏览器的通信过程:

    service = ChromeService(executable_path=ChromeDriverManager().install())
    service.log_path = "chromedriver.log"
    

    运行后查看chromedriver.log,确认浏览器是否正常启动、Driver是否能与之建立连接。

  5. 调整Driver初始化位置
    将Driver初始化移至测试函数内部,避免全局作用域下Driver提前进入异常状态:

    def test_logo_presence():
        driver = None
        try:
            service = ChromeService(executable_path=ChromeDriverManager().install())
            driver = webdriver.Chrome(service=service, options=chrome_options)
            driver.get("http://localhost:8080/")
            logo = WebDriverWait(driver, 20).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#logo a"))
            )
            assert logo is not None, "Logo不存在"
            print("测试1:Logo存在")
        except Exception as e:
            print(f"发生错误:{e}")
        finally:
            if driver:
                driver.quit()
    
  6. 检查防护软件拦截
    临时关闭杀毒软件或Windows防火墙测试,若恢复正常则将ChromeDriver和Chrome添加至防护信任列表,避免本地通信被拦截。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 05:42:14