
本文介绍在 linux 环境下使用 python 运行多个 selenium 自动化实例时,因端口冲突或驱动资源争用导致“connection refused”错误的根本原因及可靠解决方案,推荐采用 seleniumbase 的 uc 模式替代 undetected-chromedriver。
本文介绍在 linux 环境下使用 python 运行多个 selenium 自动化实例时,因端口冲突或驱动资源争用导致“connection refused”错误的根本原因及可靠解决方案,推荐采用 seleniumbase 的 uc 模式替代 undetected-chromedriver。
在多进程或多线程场景下,直接复用 undetected-chromedriver(UCD)启动多个 Chrome 实例极易引发 Connection refused 错误(如 HTTPConnectionPool(host='localhost', port=44073): Max retries exceeded),其本质并非网站封禁或代理失效,而是 UCD 内部共享的 Chromium 启动机制存在线程/进程不安全问题:它默认复用全局 ChromeDriver 服务、监听固定调试端口,且未对并发会话做隔离处理——当第二个实例尝试连接已被第一个实例占用或已释放的调试端口时,便触发连接拒绝。
根本解法:切换至线程安全、会话隔离的替代方案
SeleniumBase 的 UC Mode(Driver(uc=True))是经过生产验证的成熟替代方案。它基于 undetected-chromedriver v2 深度优化,为每个 Driver 实例自动分配独立的临时用户数据目录、随机调试端口、唯一 ChromeDriver 进程,并内置反检测指纹增强,天然支持高并发启动。
✅ 正确实践示例(支持任意数量并行实例):
import sys
from concurrent.futures import ThreadPoolExecutor
from seleniumbase import Driver
# 启用 SeleniumBase 线程安全锁(关键!防止资源竞争)
sys.argv.append("-n")
def launch_browser(url):
# 每个实例独占资源:独立 profile + 随机 debug port + 单独 chromedriver 进程
driver = Driver(uc=True, headless=True) # 可设 headless=False 调试
try:
# uc_open_with_reconnect 自动处理常见反爬重连(如 Cloudflare、PerimeterX)
driver.uc_open_with_reconnect(url, reconnect_attempts=4)
driver.sleep(3) # 替换为显式等待更佳
print(f"✅ Success on {url} (PID: {driver.service.process.pid})")
except Exception as e:
print(f"❌ Failed on {url}: {e}")
finally:
driver.quit() # 确保彻底释放所有资源(含临时目录)
# 并发启动 5 个实例(可扩展至 10+,取决于系统内存)
urls = ["https://httpbin.org/ip"] * 5
with ThreadPoolExecutor(max_workers=5) as executor:
executor.map(launch_browser, urls)
⚠️ 关键注意事项:
- 必须添加 sys.argv.append("-n"):启用 SeleniumBase 的线程锁机制,避免多线程下 ChromeDriver 二进制文件被重复覆盖;
- 禁止复用 Driver 实例:每个线程/进程必须创建独立 Driver() 对象,不可跨线程传递;
- 代理配置方式不同:若需代理,改用 Driver(uc=True, proxy="user:pass@host:port"),而非手动配置 Chrome options(UC Mode 会自动注入代理到隐身模式);
- 资源监控建议:并发数不宜超过 CPU 核心数 × 2,每实例约占用 300–500MB 内存,可通过 ps aux | grep chrome 验证进程隔离性;
- 替代方案对比:selenium-wire 或 playwright 亦可实现并发,但 SeleniumBase UC Mode 在反检测强度与易用性上更平衡。
通过该方案,你将彻底规避 Connection refused 错误,获得稳定、可扩展、反检测兼容的多实例自动化能力。











