【问题标题】:Running Selenium in headless mode via Linux causes errors通过 Linux 在无头模式下运行 Selenium 会导致错误
【发布时间】:2021-10-24 13:11:06
【问题描述】:

我在网站上运行了大量测试。 当我在 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();

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

如何让无头测试更稳定?

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

【问题讨论】:

    标签: java selenium jenkins google-chrome-headless headless-browser


    【解决方案1】:

    实际上,Selenium 社区已知的问题是 headless 并不稳定,请阅读此处about the issue more

    激活无头模式后,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 在 headless 模式下很慢

    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");
    

    【讨论】:

    • 添加这些参数会导致 Selenium 在无头模式下始终保持稳定吗?每个参数的含义是什么?
    • 首先确保你有最新的稳定的chromedriver,然后确保设置大小之后你应该等待,因为在无头模式下HTTP响应不会有很大的头大小所以它非常快,同步放置适当的延迟。
    【解决方案2】:

    您可能缺少设置无头窗口大小。
    试试这个设置:

    Map<String,String> prefs = new HashMap<>();
    prefs.put("download.default_directory", downloadsPath); // Bypass default download directory in Chrome
    prefs.put("safebrowsing.enabled", "false"); // Bypass warning message, keep file anyway (for .exe, .jar, etc.)
    ChromeOptions opts = new ChromeOptions();
    opts.setExperimentalOption("prefs", prefs);
    opts.addArguments("--headless", "--disable-gpu", "--window-size=1920,1080","--ignore-certificate-errors","--no-sandbox", "--disable-dev-shm-usage");
    
    driver = new ChromeDriver(opts);
    

    在这里,我为无头 chrome 设置了更多我使用的设置。
    我希望这对你有用。

    【讨论】:

      【解决方案3】:

      请在 chrome 选项中包含屏幕尺寸。

      ChromeOptions options = new ChromeOptions();
      options.addArguments(Arrays.asList("--window-position=0,0"));
      options.addArguments(Arrays.asList("--window-size=1840,1080"));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-22
        • 2019-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-13
        • 1970-01-01
        相关资源
        最近更新 更多