不使用xvfb运行Selenium无头

时间:2009-12-27 16:49:16

标签: testing selenium headless

我正在尝试运行Selenium无头(没有浏览器出现)。其他问题指出xvfb是执行此操作的工具。然而,它看起来非常不稳定,一直在崩溃,所以我正在寻找另一种选择。

是否有非xvfb方式运行Selenium无头?

3 个答案:

答案 0 :(得分:13)

我认为如果不运行X服务器,您将无法运行浏览器。

如果您不喜欢Xvfb,那么正如Pascal所说,您最好的选择是运行VNC服务器 - 我个人喜欢Xtightvnc。这意味着您正在运行一个(无头)X服务器,您可以随时将其转换为VNC,以防出现问题并且您想要查看它。我总是运行一个VNC服务器,并且我正在使用指向该服务器的$ DISPLAY环境变量运行我的测试。

(有人贬低我,所以也许我应该澄清一下:像Xtightvnc这样的X11 VNC服务器与Windows或OS X上的常用VNC服务器不同,后者只是在网络上共享你现有的屏幕。不要混淆。 - ))

答案 1 :(得分:6)

我很惊讶。我已经多次使用Selenium和Xvfb而没有任何问题,而且许多其他用户也这样做了。您能更具体地了解您的设置和您遇到的问题吗?你是如何开始Xvfb的?你能提供xvfb.log吗?

但是,要回答您的问题,可以使用X VNC服务器。有关说明,请参阅示例this page。如果没有关于配置的任何细节,实际上很难更准确。

答案 2 :(得分:0)

使用--headless运行chrome浏览器,它还允许您减少资源使用。使用 ChromeOptions.addArguments(“ - headless”,“window-size = 1024,768”,“ - no-sandbox”) 实现它。此方案假定安装了Chrome浏览器和Chromedriver。

这是我在Jenkins工作中使用的简单的Selenium java测试

    package com.gmail.email;

import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class FirstTest {
    private static ChromeDriver driver;
    WebElement element;

    @BeforeClass
    public static void openBrowser(){

        ChromeOptions ChromeOptions = new ChromeOptions();
        ChromeOptions.addArguments("--headless", "window-size=1024,768", "--no-sandbox");
        driver = new ChromeDriver(ChromeOptions);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test // Marking this method as part of the test
    public void gotoHelloWorldPage() {
        // Go to the Hello World home page
        driver.get("http://webapp:8080/helloworld/");

        // Get text from heading of the Hello World page
        String header = driver.findElement(By.tagName("h2")).getText();
        // Verify that header equals "Hello World!"
        Assert.assertEquals(header, "Hello World!");

    }

    @AfterClass
    public static void closeBrowser(){
        driver.quit();
    }
}

这里有更多细节 https://github.com/SeleniumHQ/docker-selenium/issues/429