如何通过 Java 使用 Selenium 将功能和选项传递到 Firefoxdriver

How to pass the capabilities and options into Firefoxdriver using Selenium through Java

我有这个:

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() from MutableCapabilities Class将DesiredCapabilities类型的对象合并到FirefoxOptions类型的对象中并初始化WebDriverWebClient 实例通过传递 FirefoxOptions 对象如下:

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);

参考资料

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

您可以将功能传递给 firefoxoptions constructor,如下所示:

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);

   FirefoxOptions options = new FirefoxOptions(capabilities);

set profile to firefox options
   options.setProfile(profile);
   options.setLogLevel(Level.FINEST);
   options.addPreference("browser.link.open_newwindow", 3);
   options.addPreference("browser.link.open_newwindow.restriction", 0);
pass firefox options as parameter to create driver
   WebDriver driver = new FirefoxDriver(options);