Selenium:setHeadless()对ChromeDriver无效

问题描述 投票:1回答:2

我正在尝试在headless mode中使用Chrome进行Selenium测试。这是我做的:

public static void main(String[] args) throws Exception {
    RemoteWebDriver driver = new ChromeDriver(new ChromeOptions().setHeadless(true));
    try {
        driver.navigate().to("https://example.com/");
        File file = driver.getScreenshotAs(OutputType.FILE);
        Files.copy(file.toPath(), Paths.get("target/screenshot.png"), StandardCopyOption.REPLACE_EXISTING);

        // adding a delay to visually check whether there is a browser window
        Thread.sleep(1000);
    } finally {
        driver.close();
    }
}

我在setHeadless(true)实例上使用ChromeOptions,但是当我运行它时,Chrome窗口弹出。看起来Chrome忽略了无头的设置。

问题是:为什么Chrome会忽略该设置以及如何让它尊重它?

我在Ubuntu Linux 16.04下使用Chrome 63.0.3239.108,一个官方的64位版本。 Selenium的版本为3.8.1。

这是我的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.rpuch.test</groupId>
    <artifactId>test-selenium-headless-chrome</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.8.1</version>
        </dependency>
    </dependencies>

</project>

该项目可在Github上找到:https://github.com/rpuch/test-selenium-headless-chrome

java google-chrome selenium selenium-chromedriver
2个回答
1
投票

事实证明,我系统中安装的chromedriver有点过时了:版本为2.30。可能它不支持“无头”功能(这在Chrome本身是最新的)。

使用最新版本的chromedriver(2.34),一切都按预期工作:我没有看到任何浏览器窗口,但屏幕截图已成功创建。


0
投票

根据google,chrome中的无头功能在版本59之后实现。和ChromeDriver v2.30应该支持这个,但根据上面的参考,

ChromeDriver 2.32使用Chrome 61,适用于无头Chrome。

© www.soinside.com 2019 - 2024. All rights reserved.