Robot Framework执行Close All Browsers报NewConnectionError WinError 10061求助
问题详情
执行Close All Browsers关键字时出现连接拒绝错误,错误日志如下:
DEBUG : Closing all browsers. DEBUG : DELETE http://127.0.0.1:50158/session/729684d022e2dd5a3b605c08363498a2 {} DEBUG : Resetting dropped connection: 127.0.0.1 DEBUG : Incremented Retry for (url='/session/729684d022e2dd5a3b605c08363498a2'): Retry(total=2, connect=None, read=None, redirect=None, status=None) WARN : Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000261F85F9508>: Failed to establish a new connection: [WinError 10061] Unable to connect because the target computer is refusing the connection.')': /session/729684d022e2dd5a3b605c08363498a2 DEBUG : Starting new HTTP connection (2): 127.0.0.1:50158 DEBUG : Incremented Retry for (url='/session/729684d022e2dd5a3b605c08363498a2'): Retry(total=1, connect=None, read=None, redirect=None, status=None) WARN : Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x00000261F86A5D88>: Failed to establish a new connection: [WinError 10061] Unable to connect because the target computer is refusing the connection.')': /session/729684d022e2dd5a3b605c08363498a2 ... 20240119 15:31:59.385 : DEBUG : Finished Request
已排查:Windows防火墙/代理无异常、浏览器驱动版本匹配且能正常启动浏览器、Selenium v3.141.0 + Robot Framework v4.0版本兼容、目标端口未被占用,但问题仍存在。
可行解决方案
检查浏览器会话是否提前终止
在执行Close All Browsers前,先用Get Window Handles确认是否存在活跃窗口,或通过Process Library的Process Is Running检查浏览器进程(如chrome.exe、firefox.exe)是否存活。若进程已不存在,直接跳过Close All Browsers操作,避免无效的连接请求。显式设置连接超时与重试策略
初始化浏览器时增加超时参数:Open Browser ${URL} ${BROWSER} timeout=5;若使用Python环境,可修改urllib3的重试配置,减少重试次数(比如将total设为0),避免反复尝试连接已失效的会话。强制终止浏览器进程
若会话已失效,直接用Process Library的Kill Process关键字强制关闭所有浏览器进程,再执行后续清理操作。示例:*** Settings *** Library Process *** Test Cases *** Cleanup Browsers Kill Process chrome.exe ignore_non_existent=True Kill Process chromedriver.exe ignore_non_existent=True改用独立Selenium Server管理会话
手动启动Selenium Server(如java -jar selenium-server-standalone-3.141.59.jar),在测试脚本中指定远程连接地址:Open Browser ${URL} ${BROWSER} remote_url=http://localhost:4444/wd/hub,便于监控服务器状态,避免驱动进程意外崩溃导致的连接问题。清理浏览器临时数据
初始化浏览器时指定临时用户数据目录,确保每次测试环境干净:Open Browser ${URL} Chrome chrome_options=add_argument("--user-data-dir=C:/Temp/ChromeTestProfile")测试结束后删除该临时目录,避免残留缓存干扰后续会话。
内容的提问来源于stack exchange,提问作者Kai Fang

