运行多实例Selenium时出现连接错误,请求技术支持
在Linux系统上使用Python 3结合undetected_chromedriver运行Selenium自动化脚本,同时配置代理。单个实例运行时一切正常,但启动第二个实例时出现以下错误:
2024-04-30 00:09:28 - ERROR - HTTPConnectionPool(host='localhost',port=44073): Max retries exceeded with url:/session/2488e939aa54121cb42b165948495489/actions (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7debd7c86fb0>: Failed to establish a new connection: [Errno 111] Connection refused'))
已尝试的解决方案:
- 将脚本拆分后在不同终端运行
- 分别启动带代理和不带代理的实例
- 针对scrapeme网站进行自动化测试,排除网站拦截因素,但问题依旧
无法定位错误根源,寻求解决办法。
1. 为每个实例分配独立的用户数据目录
undetected_chromedriver默认可能共享用户数据目录,多实例运行时会引发资源冲突。初始化驱动时指定专属目录:
import undetected_chromedriver as uc from selenium.webdriver.chrome.options import Options def init_driver(proxy): opts = Options() # 用代理信息生成唯一目录名,避免重复 profile_dir = f"/tmp/chrome_profile_{proxy.replace(':', '_')}" opts.add_argument(f"--user-data-dir={profile_dir}") opts.add_argument(f"--proxy-server={proxy}") # 禁用/dev/shm共享,解决Linux下资源限制问题 opts.add_argument("--disable-dev-shm-usage") driver = uc.Chrome(options=opts) return driver
2. 手动指定调试端口,避免端口冲突
默认随机端口可能出现分配异常,手动为每个实例指定不同端口:
def init_driver(proxy, debug_port): opts = Options() opts.add_argument(f"--proxy-server={proxy}") opts.add_argument(f"--remote-debugging-port={debug_port}") opts.add_argument(f"--user-data-dir=/tmp/chrome_profile_{debug_port}") driver = uc.Chrome(options=opts, port=debug_port) return driver # 调用时使用不同端口,如9222、9223 driver1 = init_driver("http://proxy1:8080", 9222) driver2 = init_driver("http://proxy2:8080", 9223)
3. 验证代理的并发连接能力
部分代理限制同时连接数,导致第二个实例无法建立连接。先测试代理可用性:
import requests def check_proxy(proxy): try: resp = requests.get("http://httpbin.org/ip", proxies={"http": proxy, "https": proxy}, timeout=5) return resp.status_code == 200 except Exception: return False # 创建驱动前先验证 proxy = "http://proxy1:8080" if check_proxy(proxy): driver = init_driver(proxy, 9222) else: print(f"Proxy {proxy} is not working")
4. 确保进程完全销毁
第一个实例结束时,Chrome进程可能未彻底关闭,占用资源导致后续实例失败。脚本结束时显式退出驱动:
try: # 执行自动化逻辑 driver.get("https://scrapeme.live/shop/") finally: driver.quit() # 彻底关闭进程,而非仅关闭窗口
5. 更新依赖版本
旧版本undetected_chromedriver或Chrome浏览器可能存在多实例兼容性问题,更新到最新版本:
pip install --upgrade undetected-chromedriver
同时确保Chrome浏览器是最新版本,保持驱动与浏览器版本匹配。
内容的提问来源于stack exchange,提问作者Wajih Wanis

