Java Selenium 如何为新驱动程序设置动态变量

Java Selenium how to set a dynamic variable for new driver

我知道在 java 中不可能使用条件块中的变量。 但我不知道该怎么办。当我这样做时,if 语句后的代码出现错误:

public static void startDriver(String preferredBrowser) throws Exception{
    Webdriver driver;

    if(preferredBrowser.equals("Firefox")){

    } 
    else if(preferredBrowser.equals("Edge")){

    }
    else{
        System.setProperty("webdriver.chrome.driver",  driverPath);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);

        driver = new ChromeDriver(options);
    }
    driver.manage().window().maximize();
    driver.get(website);

}

这是我试图修复它的方法,但现在它确实同时打开了两个驱动程序:

public static void startDriver(String preferredBrowser) throws Exception{
    System.setProperty("webdriver.chrome.driver",  driverPath);
    WebDriver driver = new ChromeDriver();
    if(preferredBrowser.equals("Firefox")){

    } 
    else if(preferredBrowser.equals("Edge")){

    }
    else{
        System.setProperty("webdriver.chrome.driver",  driverPath);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);

        driver = new ChromeDriver(options);
    }
    driver.manage().window().maximize();
    driver.get(website);

}

希望你能帮帮我。

此致

基督教徒

您可以为每个 preferredBrowser 初始化驱动程序类型,如下所示:

public static void startDriver(String preferredBrowser) throws Exception{
    Webdriver driver;

    if(preferredBrowser.equals("Firefox")){
        driver = new FirefoxDriver();
    } 
    else if(preferredBrowser.equals("Edge")){
            driver = new EdgeDriver();
    }
    else{
        System.setProperty("webdriver.chrome.driver",  driverPath);
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        options.setExperimentalOption("useAutomationExtension", false);

        driver = new ChromeDriver(options);
    }
    driver.manage().window().maximize();
    driver.get(website);
}