我想将ChromeDriverService
与chromeOptions
或DesiredCapabilities
合并,以便在xvfb中运行浏览器。
下面是我之前没有使用selenium网格的代码ChromeDriverService
的一部分。
String NodeChromeIncognito = "http://localhost:5558/wd/hub"
ChromeDriverService chromeDriverService = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("driver_linux/chromedriver"))
.usingAnyFreePort()
.withEnvironment(ImmutableMap.of("DISPLAY", ":1")).build();
chromeDriverService.start();
// commented because using RemoteWebDriver
// driver = new ChromeDriver(chromeDriverService);
及以下是RemoteWebDriver的部分代码,我将与ChromeDriverService
合并。
DesiredCapabilities cap = null;
String NodeChromeIncognito = "http://localhost:5558/wd/hub";
String NodeChrome = "http://localhost:5557/wd/hub";
String NodeFirefox = "http://localhost:5556/wd/hub";
if (browserName.equals("chrome")) {
cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
driver = new RemoteWebDriver(new URL(NodeChrome), cap);
} else if (browserName.equals("firefox")) {
System.setProperty("webdriver.gecko.driver", "driver_linux/geckodriver");
cap = DesiredCapabilities.firefox();
cap.setCapability("marionette", true);
driver = new RemoteWebDriver(new URL(NodeFirefox), cap);
}else if (browserName.equals("chromeIncognito")) {
ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
cap = DesiredCapabilities.chrome();
cap.setCapability(ChromeOptions.CAPABILITY, option);
cap.setPlatform(Platform.WIN10);
cap.setBrowserName("chrome incognito");
driver = new RemoteWebDriver(new URL(NodeChromeIncognito), cap);
}
我知道我可以将addArguments("--headless")
用于Chrome,但它对我的webApp不起作用。我还使用了DesiredCapabilities.merge
和错误。
如何将代码/配置ChromeDriverService
与ChromeOptions
或DesiredCapabilites
合并?
答案 0 :(得分:0)
如您所述,您希望将 ChromeDriverService
与 ChromeOptions
或 DesiredCapabilities
合并可以实现。但截至目前 Selenium Java Client
发布时,以下构造函数 已弃用:
ChromeDriver(Capabilities capabilities)
//and
ChromeDriver(ChromeDriverService service, Capabilities capabilities)
因此我们必须使用以下任一选项:
选项A:仅使用ChromeOptions
:
private static ChromeDriverService service;
private WebDriver driver;
//code block
service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("path/to/my/chromedriver.exe"))
.usingAnyFreePort()
.build();
chromeDriverService.start();
ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
driver = new RemoteWebDriver(service.getUrl(), options);
选项B:使用DesiredCapabilities
,然后使用MutableCapabilities
中的merge()
合并到ChromeOptions
:
private static ChromeDriverService service;
private WebDriver driver;
//code block
service = new ChromeDriverService.Builder()
.usingDriverExecutable(new File("path/to/my/chromedriver.exe"))
.usingAnyFreePort()
.build();
chromeDriverService.start();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("...", true);
ChromeOptions option = new ChromeOptions();
option.addArguments("--incognito");
option.merge(capabilities);
driver = new RemoteWebDriver(service.getUrl(), options);