Selenium如何关闭Chrome浏览器并打开新的One

时间:2016-06-07 03:41:22

标签: java selenium-webdriver selenium-chromedriver

我的方案是关闭Chrome浏览器并打开一个新浏览器。

public String openNewBrowserWindow() {
    this.log("Opening new Browser window...");
    String stringHandles;
    Set<String> previousWindows = driver.getWindowHandles();
    String previousHandle = driver.getWindowHandle();
    ((JavascriptExecutor)driver).executeScript("window.open();");
    Set<String> newWindows = driver.getWindowHandles();
    newWindows.removeAll(previousWindows);
    String newHandle = ((String)newWindows.toArray()[0]);
    stringHandles = previousHandle + ";" + newHandle;
    return stringHandles;
}

我做的是:

String handlesA = generic.openNewBrowserWindow();
String[] handleA = handlesA.split(";");
generic.closeBrowser();
generic.switchToWindow(handleA[1]);

这适用于Firefox,但不适用于chrome。你们有什么建议吗?

2 个答案:

答案 0 :(得分:4)

为什么不呢:

driver.quit()
driver = new ChromeDriver()

你的情景是什么真的

答案 1 :(得分:3)

@Seimone 每当您想要启动Chrome浏览器时,必须将系统属性定义为chromedriver.exe

System.setProperty("webdriver.chrome.driver", driverPath+"chromedriver.exe");
WebDriver driver = new ChromeDriver();

此外,如果要关闭当前的Chrome浏览器窗口,请在代码中使用以下内容。

driver.close();

如果要关闭所有Chrome浏览器窗口,请在代码中使用以下内容。

driver.quit();

参考您的方案

1.打开网址 2.登录登录。 3.关闭浏览器。 4.打开浏览器并输入相同的URL。 5.检查同一用户是否已登录。

尝试以下代码并告诉我您的结果。

String chromeDriver = "enter the chromedriver.exe path";
String chromeProfile = "C:/Users/MSTEMP/AppData/Local/Google/Chrome/User Data/Default"; //Local chrome profile path.
System.setProperty("webdriver.chrome.driver", chromeDriver);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
options.addArguments("start-maximized");
options.addArguments("user-data-dir="+chromeProfile);
capabilities.setCapability("chrome.binary",chromeDriver);
capabilities.setCapability(ChromeOptions.CAPABILITY,options);
WebDriver driver = new ChromeDriver(capabilities);

driver.get("https://www.gmail.com");
/*write your login credentials code with username, password and perform the
login operation with signed in*/
driver.close();

//Now invoke the chrome browser and enter the url alone.
driver = new ChromeDriver(capabilities);
driver.get("http://www.gmail.com");
//write the code for user signed verification.