使用Selenium Webdriver将控制切换到模态窗口(而不是警报)

时间:2014-01-30 10:19:53

标签: selenium modal-dialog selenium-webdriver

当我点击“保存”按钮时,我有一个启动“保存窗口”(即模态)的Web应用程序。这个窗口需要10秒才能完全加载(我可以通过等待来解决这个问题)。 在完成保存之前,我需要在此窗口中执行一些操作。

我面临的问题是 - 模态窗口启动的那一刻,我无法使用driver.SwitchTo()或driver.Manage()。GetAllWindowHandles()等。我用以下代码行确认了这一点。

driver.findElement(By.xpath("//*[@id='toolbar']/a[1]")).click();
// After the above line is executed, the Popup gets launched

Set<String> sWindowHandles = driver.getWindowHandles();
System.out.println("Popup"); 
System.out.println(driver.getWindowHandles().size()); // This always prints "1"

在我明确关闭弹出窗口之前,上面的3行根本没有执行(或者至少不会执行很长时间)。

当我无法找到Window的处理程序时,如何处理保存窗口(模态)中存在的某些控件?

for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

不起作用,因为在打开模态窗口后立即启动(仅在启动后才对GetWindowHandles有意义),后续行根本不会执行。 我陷入僵局。请帮帮我。

2 个答案:

答案 0 :(得分:0)

如果Windows句柄无法处理应用程序 可以使用Java机器人类功能。

      Robot robot = new Robot();   
//Doing a mouse over for the X and Y coordinates of button/link which opens modal window
robot.mouseMove(210,350);  
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);  
robot.delay(100);  
//Clicking tab til the cursor is on specific position (textbox/button)
robot.keyPress(KeyEvent.VK_TAB);  
robot.delay(100);  
//Doing a mouse over for the X and Y coordinates of button/link
robot.mouseMove(300,150);  
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);  
robot.delay(100);

有关更多信息,请参阅以下链接。 http://alvinalexander.com/java/java-robot-class-example-mouse-keystroke

答案 1 :(得分:0)

即使弹出窗口可见,我有时会发现窗口句柄可能需要一段时间才能使用正确的值进行更新。为了解决这个问题,我使用了一个循环,当窗口句柄达到预期大小时,循环会中断。