切换窗口在硒中

时间:2015-10-29 08:17:24

标签: java selenium-webdriver

切换场景 我的应用程序中有3个窗口 点击我的第一个窗口窗口将打开,切换代码在这里工作正常 现在当前控制在第2页(窗口)。在第二个窗口中还有一个按钮,它将打开第三个窗口。我想切换到第3个窗口,但不想关闭我的第1个或第2个窗口。当我打电话给那个切换方法时......它没有工作 我可以切换到3个Windows ...?如果我将关闭第二个窗口然后开启第三个窗口,但这里要求我不想关闭第一个或第二个窗口

以下是我正在使用的代码

public static void switchWindow() throws InterruptedException{

window = driver.getWindowHandle(); 
Set<String> allWin = driver.getWindowHandles();
for (String wh : allWin)
{
driver.switchTo().window(wh);
System.out.println(driver.getTitle());
}
}

public static void backtomainWindow()
{
//driver.close();
driver.switchTo().window(window);
}

我收到了例外org.openqa.selenium.NoSuchWindowException: Window not found. The browser window may have been closed.

1 个答案:

答案 0 :(得分:3)

以下是您的查询解决方案 -

public static WebDriver driver;
public static String strMainWindowHandle;
public static Map<String, String> lstWindowData;

public static void main(String[] args) throws Exception {


    driver = new FirefoxDriver();

    driver.navigate().to("url");
    strMainWindowHandle = driver.getWindowHandle();

    //button 1 (on parent window - window 1)
    driver.findElement(By.cssSelector("button_1")).click();
    switchToLatestWindow();

    //button 2 (on next window - window 2)
    driver.findElement(By.cssSelector("button_2")).click();
    switchToLatestWindow();

    //button 3 (on next window - window 3)
    //Same as above ... and so on...

    //Now to switch back to parent Window
    switchToParentWindow();

    //All spawned windows are still open
    //so if you wish to switch to a specific window "by Title"
    switchToSpecificWindow("WindowTitle");


}

public static void switchToLatestWindow() throws InterruptedException{

    Set<String> setAllWindows = driver.getWindowHandles();
    for (String windowHandle : setAllWindows)
    {
        if(!windowHandle.equals(strMainWindowHandle) && !lstWindowData.containsValue(windowHandle)){
            driver.switchTo().window(windowHandle);
            String strTitle = driver.getTitle();
            System.out.println(strTitle);
            //map will be useful later...
            lstWindowData.put(strTitle, windowHandle);
        }
    }
}

public static void switchToSpecificWindow(String strWindowTitle) throws InterruptedException {

    String strRequiredHandle = lstWindowData.get(strWindowTitle);
    Set<String> setAllWindows = driver.getWindowHandles();

    for(String windowHandle : setAllWindows){
        if(windowHandle.equals(strRequiredHandle)){
            driver.switchTo().window(windowHandle);        
        }
    }        
}

public static void switchToParentWindow()
{
    driver.switchTo().window(strMainWindowHandle);
}