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

2022-09-02 23:24:23

这是我的代码:

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 毫秒。

有什么想法吗?


答案 1

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

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

答案 2

我有一个实用程序方法可以切换到所需的窗口,如下所示

public class Utility 
{
    public static WebDriver getHandleToWindow(String title){

        //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
        WebDriver popup = null;
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
          String windowHandle = s; 
          popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
          System.out.println("Window Title : " + popup.getTitle());
          System.out.println("Window Url : " + popup.getCurrentUrl());
          if (popup.getTitle().equals(title) ){
              System.out.println("Selected Window Title : " + popup.getTitle());
              return popup;
          }

        }
                System.out.println("Window Title :" + popup.getTitle());
                System.out.println();
            return popup;
        }
}

一旦窗口的标题作为参数传递,它将带您进入所需的窗口。在你的情况下,你可以做到。

Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");

然后使用相同的方法再次切换到父窗口

Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");

此方法在处理多个窗口时有效。


推荐