如何在Selenium-Java 3.11中将DesiredCapabilities添加到GeckoDriver

时间:2018-04-19 09:18:57

标签: java selenium selenium-webdriver geckodriver mutablecapabilities

我试图在GeckoDriver中使用selenium-java 3.11 for firefox。 firefox版本为59。事情很好,我可以调用firefox驱动程序。唯一的挑战是我需要将DesiredCapabilities添加到我的firefox实例。

最新的selenium版本中的旧方法WebDriver driver = new FirefoxDriver(capabilities);似乎已被弃用,并且无法找出指定功能的新方法。

以下是代码:

public static WebDriver createDriver(String userAgentKey, String PROXY) {


     File modifyHeaders = null;
     try {
     modifyHeaders =
     ResourceUtils.getFile("classpath:modify_headers-0.7.1.1-fx.xpi");  //am adding the extension using DesiredCapabilities
     } catch (FileNotFoundException e1) {

     e1.printStackTrace();
     }

    Proxy proxy = new Proxy();
    proxy.setHttpProxy(PROXY).setFtpProxy(PROXY).setSslProxy(PROXY);



    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("javascript.enabled", true);
    profile.setPreference("brower.link.open_newwindow", 1);


    profile.setPreference("modifyheaders.config.active", true);
    profile.setPreference("modifyheaders.config.alwaysOn", true);
    profile.setPreference("modifyheaders.headers.count", 1);
    profile.setPreference("modifyheaders.headers.action0", "Add");
    profile.setPreference("modifyheaders.headers.name0", "Proxy-Authorization");
    profile.setPreference("modifyheaders.headers.value0", "Basic dnNodWtsYUBleHBlZGlhLmNvbTpxZWxsYWZraw==");
    profile.setPreference("modifyheaders.headers.enabled0", true);

    profile.addExtension(modifyHeaders);

    DesiredCapabilities cap = DesiredCapabilities.firefox();
    cap.setCapability(FirefoxDriver.PROFILE, profile);
    cap.setCapability(CapabilityType.PROXY, proxy);
    System.setProperty("webdriver.gecko.driver","/Users/vshukla/Music/geckodriver");

    WebDriver driver = new FirefoxDriver(cap);  //this is deprecated


    return driver;

如何使用DesiredCapabilities将扩展添加到实例?有什么其他选择来实现这一目标?

2 个答案:

答案 0 :(得分:0)

使用firefox选项:

    FirefoxOptions options = new FirefoxOptions();
    options.setCapability(FirefoxDriver.PROFILE, profile);
    options.setCapability(CapabilityType.PROXY, proxy);

答案 1 :(得分:0)

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

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

System.setProperty("webdriver.gecko.driver","/Users/vshukla/Music/geckodriver");
DesiredCapabilities cap = DesiredCapabilities.firefox();
cap.setCapability(FirefoxDriver.PROFILE, profile);
cap.setCapability(CapabilityType.PROXY, proxy);
FirefoxOptions opt = new FirefoxOptions();
opt.merge(cap);
WebDriver driver = new FirefoxDriver(opt);

PS:作为参考,您可以查看mutablecapabilities代码

中的讨论