多机部署Selenium Grid 4.8.0执行Firefox测试遇SessionNotCreatedException
问题分析与解决办法
核心问题
你在测试代码里设置的System.setProperty("webdriver.firefox.marionette", "C:\\SeleniumHub4\\geckodriver.exe")只对本地生效,但Selenium Grid的节点运行在远程机器/虚拟机上,远程节点无法访问你本地的驱动文件,导致启动Firefox驱动超时,抛出SessionNotCreatedException。
解决步骤
1. 修改测试代码
删除本地的驱动路径配置,因为远程节点负责管理驱动,本地代码只需指定浏览器选项:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxOptions; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.*; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; public class ParallelTest { private WebDriver driver; @BeforeMethod public void setUp() throws MalformedURLException { if(driver == null) { String cloudUrl = "http://localhost:4444/wd/hub"; // 移除本地驱动路径设置 FirefoxOptions browserOptions = new FirefoxOptions(); driver = new RemoteWebDriver(new URL(cloudUrl), browserOptions); } } @Test public void test1() { driver.get("https://www.google.com"); Date fecha = new Date(); System.out.println(fecha + " Test 1 executed on: " + ((RemoteWebDriver) driver).getCapabilities().getBrowserName()); } @Test public void test2() { driver.get("https://www.facebook.com"); Date fecha = new Date(); System.out.println(fecha + " Test 2 executed on: " + ((RemoteWebDriver) driver).getCapabilities().getBrowserName()); } @AfterSuite public void tearDown() { driver.quit(); driver = null; } }
2. 配置远程节点
每个远程节点机器需完成以下操作:
- 安装对应版本的Firefox浏览器
- 下载与Firefox版本匹配的geckodriver,存放至节点机器的本地路径
- 启动节点时指定驱动路径,或把驱动所在路径加入系统环境变量
PATH
方式一:启动节点时指定驱动路径
java -jar selenium-server-4.8.0.jar node --hub http://<hostIP>:4444 --driver-path "C:\SeleniumHub4\geckodriver.exe"
(替换为节点机器上geckodriver的实际路径)
方式二:将驱动加入系统PATH
把geckodriver所在文件夹添加到节点机器的系统环境变量PATH中,启动节点时无需额外指定路径,保持原命令即可:
java -jar selenium-server-4.8.0.jar node --hub http://<hostIP>:4444
3. 额外注意事项
- 确保Firefox浏览器与geckodriver版本兼容,版本不匹配会导致驱动启动失败
- 节点机器的防火墙需允许与hub的4444端口通信
- 测试代码中的
cloudUrl要指向hub的实际IP,不要用localhost(除非节点与hub在同一机器)
内容的提问来源于stack exchange,提问作者cagoscra
相关产品推荐
相关产品推荐

