java - Selenium 中的多个选项卡

标签 java selenium-webdriver

我有一个问题,请您解释一下。

为什么在打开第二个和第三个窗口时我们要调用 getWindowHandles 以下内容

win = driver.getWindowHandles();
iterate = win.iterator();
first_window = iterate.next();
System.out.println(first_window);  // first handle
second_window = iterate.next();
System.out.println(second_window);  // second handle

在第三个窗口运行的时候,我们不能直接调用下面的方法吗

String Third_window = iterate.next();
System.out.println(Third_window);
driver.switchTo().window(Third_window);

最佳答案

每当您的 Web 应用程序在您浏览时有多个窗口时,我们就需要使用 getWindowHandles() 方法来处理多个窗口。它返回通过 Webdriver 对象的任何链接/按钮单击打开或关联或实例化的每个窗口的唯一字母数字 ID(字符串对象)。

getWindowHandles() 返回当前所有窗口的窗口句柄列表。

因此,每当您在驱动程序对象上调用 getWindowHandles() 时。它存储所有打开的窗口的唯一窗口句柄,包括您的父窗口句柄。您可以在循环内一一切换到每个窗口并查找特定的网络元素,如果找到,您可以在该窗口上工作(在您的情况下是第三个窗口)。通过这样做,您将确保您的代码将在正确的窗口上运行,而不仅仅是基于假定的窗口编号。此外,您还需要存储父窗口句柄,以便在其他窗口上的工作完成后可以切换回来。

代码:

String parentWindowHandle = driver.getWindowHandle();
Set<String> childWindows = driver.getWindowHandles();
Iterator<String> iterator = childWindows.iterator();


while(iterator.hasNext())
{
    String child = iterator.next();

    if(!child.equalsIgnoreCase(parentWindowHandle))
    {
        driver.switchTo().window(child);
        try
        {
            if (driver.findElement(By.id("id_of_some_element_on_that_window")).isDisplayed())
            {
                break;
            }
        }
        catch(Exception e) // you can catch the specific exoection NoSuchElement or other
        {
            System.out.println("Element not found."+e.getMessage());
        }

    }
}

// rest of code to work on desired window

driver.switchTo().window(parentWindowHandle);

希望这有帮助:)

关于java - Selenium 中的多个选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369243/

相关文章:

java - 在Blackberry4.6操作系统版本上加载html

java - 自定义等待 try catch webdriver

javascript - 如何在 javascript 语言绑定(bind)中使用 RemoteWebDriver? (在 Node.js 上运行)

java - 如何在类的注释内编写注释?

java - 加权无向图上的最长路径

Javadoc "ı" "i"问题

java - sun.net.www.protocol.https.HttpsURLConnectionImpl 无法转换为 sun.net.www.protocol.http.HttpURLConnection

node.js - 如何通过 Selenium 根据 HTML 定位文本为 My Name 的元素

selenium - 在使用相同的 xpath 定位元素时获取 InvalidSelectorException,该 xpath 在具有 1 个匹配节点的 firepath 中运行良好

selenium - NoSuchElementException,Selenium 无法定位元素