我们在driver.getWindowhandles()中获得的Set是否保留顺序

A.J*_*A.J 5 selenium selenium-webdriver

我有一个困惑是,在selenium中返回窗口句柄的集合是否保持打开窗口的顺序,我的意思是第一个窗口将在第一个位置,下一个窗口在下一个位置打开,依此类推.

这是代码:

Set<String> handles = driver.getWindowhandles()
Run Code Online (Sandbox Code Playgroud)

Deb*_*anB 0

首先让我们看一下getWindowhandles()方法的调用。

获取窗口句柄

很明显,该getWindowhandles()方法返回一个Setof 类型String,因此当我们提到时,我们几乎是正确的:

Set<String> handles = driver.getWindowhandles();
Run Code Online (Sandbox Code Playgroud)

现在,我将把我的答案限制为,Mozilla Firefox因为它遵循与 内联的独特规范W3C Specs

其中WebDriver W3C Specification明确提到了以下内容:

The Get Window Handles command returns a list of window handles for every open top-level browsing context. The order in which the window handles are returned is arbitrary.

关于窗户把手WebDriver W3C Specification清楚地说:

Each browsing context has an associated window handle which uniquely identifies it. This must be a String and must not be "current"

The web window identifier is the string constant "window-fcc6-11e5-b4f8-330a88ab9d7f"

因此我们可以得出结论,订单未被保留。

解决方案:

在这种情况下,如果我们需要将 Selenium 的焦点从第一个窗口转移到第二个窗口,然后转移到第三个窗口并遍历回来,我们可以实现一个逻辑来保留中的所有窗口句柄,并在调用之前简单Set地比较window handle值,driver.switchTo().window(win_handle);如下所示:

String parent_window = driver.getWindowHandle();
System.out.println("Parent Window ID is : "+parent_window);
element2.click();   // WebElement which opens a new window
Set<String> allWindows = driver.getWindowHandles();
for(String child_1:allWindows)
    if(!parent_window.equalsIgnoreCase(child_1))
        driver.switchTo().window(child_1);
System.out.println(driver.getTitle());
String child1_window = driver.getWindowHandle();
System.out.println("Child 1 Window ID is : "+child1_window);
driver.findElement(By.linkText("Link")).click();    //Link which opens a new window
Set<String> all_Windows = driver.getWindowHandles();
for(String child_2:all_Windows)
    if(!parent_window.equalsIgnoreCase(child_2) && !child1_window.equalsIgnoreCase(child_2))
        driver.switchTo().window(child_2);
String child2_window = driver.getWindowHandle();
System.out.println("Child 2 Window ID is : "+child2_window);
Run Code Online (Sandbox Code Playgroud)