如何使用Java处理Selenium WebDriver中的新窗口?

Aru*_*mar 17 java new-window selenium-webdriver

这是我的代码:

driver.findElement(By.id("ImageButton5")).click();
//Thread.sleep(3000);
String winHandleBefore = driver.getWindowHandle();
driver.switchTo().window(winHandleBefore);
driver.findElement(By.id("txtEnterCptCode")).sendKeys("99219");
Run Code Online (Sandbox Code Playgroud)

现在我有下一个错误:

线程"main"中的异常org.openqa.selenium.NoSuchElementException:无法找到id == txtEnterCptCode的元素(警告:服务器未提供任何堆栈跟踪信息)命令持续时间或超时:404毫秒.

有任何想法吗?

COD*_*ACK 40

看起来你实际上没有切换到任何新窗口.您应该获取原始窗口的窗口句柄,保存它,然后获取新窗口的窗口句柄并切换到该窗口.完成新窗口后,需要将其关闭,然后切换回原始窗口句柄.请参阅下面的示例:

String parentHandle = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}

//code to do something on new window

driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window
Run Code Online (Sandbox Code Playgroud)