我有一个问题,请您解释一下。
为什么在打开第二个和第三个窗口时我们要调用 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/