1

我使用 Selenium 2 + Java 在 IE 9 上测试应用程序。单击链接后,弹出窗口打开。我使用 switchTo.window 方法进入弹出窗口。但是当我尝试返回时,我的测试在此操作上被延迟并且无法继续。

一些代码:

link.click(); //Open pop-up window    
Object[] windows = driverIE.getWindowHandles().toArray();    
driverIE.switchTo().defaultContent();    
driverIE.switchTo().window(windows[1].toString());  //Focus on pop-up window    
.....    
mainWindowHandle = driverIE.getWindowHandles().iterator().next();   //Handle of main window    
driverIE.switchTo().window(mainWindowHandle);   //Fail!    

请帮我解决问题。

4

2 回答 2

2

getWindowHandles()不保证返回的 Windows 句柄按任何顺序排列。换句话说,您不能依赖windows[1]上面的代码示例来包含已打开窗口的窗口句柄。相反,您需要的代码如下所示(注意:前面完全未经测试的代码!):

String mainHandle = driver.getWindowHandle();

// Do whatever you need to do to open a new window,
// and properly wait for the new window to appear...

Set<String> allHandles = driver.getWindowHandles();
for(String currentHandle : allHandles) {
  // Note that this is cheating a bit. It will only
  // work with a total of two windows. If you have
  // more than two windows total, your logic here
  // will have to be a little more sophisticated.
  if (!currentHandle.equals(mainHandle)) {
    driver.switchTo().window(currentHandle);
    break;
  }
}

// Work with popup window...
// Close the popup window and switch context back
// to the main window.
driver.close();
driver.switchTo().window(mainHandle);
于 2012-05-25T11:49:18.203 回答
0

正如 JimEvans 所说,driver.getWindowHandles() 有时会以错误的顺序放置窗口,因此 for 循环并不总是有效。

类似于上面对我有用(我只有两个窗口要处理):

    String winHandleBefore = driver.getWindowHandle();

    driver.findElement(By.cssSelector("a")).click();

    Set<String> winHandle = driver.getWindowHandles();

    winHandle.remove(winHandleBefore);

    String winHandleNew = winHandle.toString();

    String winHandleFinal = winHandleNew.replaceAll("\\[", "").replaceAll("\\]","");

    driver.switchTo().window(winHandleFinal);
于 2015-02-25T10:49:33.040 回答