当测试页面同时出现2个或者以上窗口时候,而且新打开的window没有namem,可以使用driver.switchTo().window(winHandleID)来进行切换,如下代码已经在IE8中测试通过:
//Store the current window handleString winHandleBefore = driver.getWindowHandle(); //Switch to new window openedfor(String winHandle : driver.getWindowHandles()){ System.out.println("+++" + winHandle); driver.switchTo().window(winHandle); }// Close the original window driver.switchTo().window(winHandleBefore); driver.close(); //Switch to new window openedfor(String winHandle : driver.getWindowHandles()){ System.out.println("+++" + winHandle); driver.switchTo().window(winHandle); }
当最后只有一个窗口剩下的时候,应该可以直接使用
driver.switchTo().window(driver.getWindowHandle)
去选中新的窗口
public boolean switchToWindow(WebDriver driver,String windowTitle){ boolean flag = false; try { String currentHandle = driver.getWindowHandle(); Sethandles = driver.getWindowHandles(); for (String s : handles) { if (s.equals(currentHandle)) continue; else { driver.switchTo().window(s); if (driver.getTitle().contains(windowTitle)) { flag = true; System.out.println("Switch to window: " + windowTitle + " successfully!"); break; } else continue; } } } catch (NoSuchWindowException e) { System.out.println("Window: " + windowTitle + " cound not found!", e.fillInStackTrace()); flag = false; } return flag; }