首页 > 解决方案 > 通过 Linux 在无头模式下运行 Selenium 会导致错误

问题描述

我在一个站点上运行了大量测试。当我在 Windows 上本地运行测试时,它们都 100% 通过。该测试是在 Google Chrome 上设计和运行的。

现在,我们已经开始在无头模式下通过 Jenkins 作业在 Linux 上运行测试。一些测试现在以 0% 失败或仅通过 20% 甚至 10%。在我的代码中,我通过 ID、xpath 或 css 查找元素,然后单击它们。我使用 WebDriverWait 对象来等待 - 既要元素存在又可点击。

我的代码示例:

    WebDriverWait wait = new WebDriverWait(browser, secondsToWait);
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id(elementID)));           
    lastFoundElement = wait.until(ExpectedConditions.elementToBeClickable(By.id(elementID)));
    clickLastFoundElement();

在我的报告中,我主要看到未找到元素,并且我通过了等待对象中设置的超时。

如何让无头测试更稳定?

为什么无头状态会导致这么多问题?

标签: javaseleniumjenkinsgoogle-chrome-headlessheadless-browser

解决方案


实际上,Selenium 社区已知的问题是 headless 并不稳定,请在此处阅读有关该问题的更多信息

激活无头模式后,Chrome 运行非常不稳定。有多个不同的问题和错误取决于:Chrome 版本、ChromeDriver版本和executed tests.

问题和修复(到目前为止发生):

Chrome 无法以无头模式启动

Exception:
No informative Error message. Only a timeout exception when navigate() is called on the driver:
org.openqa.selenium.TimeoutException: timeout

Fix:
options.addArguments("--proxy-server='direct://'");
options.addArguments("--proxy-bypass-list=*");

Chrome 在无头模式下非常慢

Fix:
options.addArguments("--proxy-server='direct://'");
options.addArguments("--proxy-bypass-list=*");

当测试运行很长时间时,Chrome 在一段时间后无法正常运行。在一个测试会话中执行许多操作

Exception:
... Timed out receiving message from renderer: ...
Fix (not tested yet!):
options.addArguments("--disable-browser-side-navigation");

推荐阅读