如何使用 Java 处理 Selenium WebDriver 中的新窗口? [英] How to handle the new window in Selenium WebDriver using Java?

查看:35
本文介绍了如何使用 Java 处理 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");

现在我有下一个错误:

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

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == txtEnterCptCode (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 404 milliseconds.

有什么想法吗?

推荐答案

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

It seems like you are not actually switching to any new window. You are supposed get the window handle of your original window, save that, then get the window handle of the new window and switch to that. Once you are done with the new window you need to close it, then switch back to the original window handle. See my sample below:

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

这篇关于如何使用 Java 处理 Selenium WebDriver 中的新窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆