我有这个:

System.setProperty("webdriver.gecko.driver", "gecko/linux/geckodriver");

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.no_proxies_on", "localhost");
profile.setPreference("javascript.enabled", true);

DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
capabilities.setCapability(FirefoxDriver.PROFILE, profile);

FirefoxOptions options = new FirefoxOptions();
options.setLogLevel(Level.FINEST);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 0);


现在,我有两个不同的构造函数:

WebDriver driver = new FirefoxDriver(capabilities);




WebDriver driver = new FirefoxDriver(options);


如何将它们(功能和选项)都传递给driver?顺便说一句,IDE告诉我FirefoxDriver(capabilities)已过时。

最佳答案

你快到了您需要使用merge()类中的方法MutableCapabilities将DesiredCapabilities类型的对象合并到FirefoxOptions类型的对象中,并通过传递FirefoxOptions对象来初始化WebDriver和WebClient实例,如下所示:

System.setProperty("webdriver.gecko.driver", "gecko/linux/geckodriver");

FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.no_proxies_on", "localhost");
profile.setPreference("javascript.enabled", true);

DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
capabilities.setCapability(FirefoxDriver.PROFILE, profile);

FirefoxOptions options = new FirefoxOptions();
options.merge(capabilities);
options.setLogLevel(Level.FINEST);
options.addPreference("browser.link.open_newwindow", 3);
options.addPreference("browser.link.open_newwindow.restriction", 0);

WebDriver driver = new FirefoxDriver(options);




参考文献

您可以在以下位置找到一些相关的讨论:


How to Merge Chrome driver service with desired capabilities for headless using xvfb?
How to address “The constructor ChromeDriver(Capabilities) is deprecated” and WebDriverException: Timed out error with ChromeDriver and Chrome

10-08 15:59