如何在无头模式下运行WebDriver?
如何在无头模式下运行WebDriver?如果您的CI工具(例如Jenkins)不支持UI,则可能需要这样做。在无头模式下运行WebDriver自动测试在测试执行速度和更轻松地集成到CI管道方面具有优势。下面,我们将使用PhantomJS和ChromeDriver以无头模式运行Selenium WebDriver测试。PhantomJS要使用PhantomJS以无头模式运行WebDriver测试,首先需要下载 PhantomJS可执行文件并将其保存在某个位置,例如项目的资源文件夹。在下面的示例中,我将PhantomJS可执行文件放在src / test / resources / phantomjs中您还需要ghost驱动程序依赖项:<dependency>
<groupId>com.github.detro.ghostdriver</groupId>
<artifactId>phantomjsdriver</artifactId>
<version>1.0.1</version>
</dependency>而你的Java类:package com.sdetworld.tutorials.selenium
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
public class WebDriverBase {
static protected WebDriver driver;
public static void setup() {
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true); // not really needed: JS enabled by default
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "src/test/resources/phantomjs");
driver = new PhantomJSDriver(caps);
}
public static void main(String[] args) {
WebDriverBase.setup();
driver.get("https://www.testingexcellence.com");
}
}
ChromeDriver要使用ChromeDriver在无头模式下运行WebDriver测试,您需要在pom.xml文件中添加相关的依赖项:<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>${selenium.version}</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>${webdrivermanager.version}</version>
</dependency>接下来,我们指示WebDriver管理器以无头模式启动chrome驱动程序package com.sdetworld.tutorials.selenium
import io.github.bonigarcia.wdm.ChromeDriverManager;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebDriverBase {
static protected WebDriver driver;
public static void setup() {
ChromeDriverManager.getInstance().setup();
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
driver = new ChromeDriver(chromeOptions);
}
public static void main(String[] args) {
WebDriverBase.setup();
driver.get("https://www.testingexcellence.com");
}
}
页:
[1]