【问题标题】:Why I am not able to switch to third window opened by Selenium WebDriver? I can switch to second window and perform steps but not third为什么我无法切换到 Selenium WebDriver 打开的第三个窗口?我可以切换到第二个窗口并执行步骤,但不能执行第三个
【发布时间】:2021-03-22 19:52:28
【问题描述】:

下面是我的代码:

//此点击打开第二个窗口。 page 是页面对象引用,并编写了单击按钮的方法

public enterDetails(String fname)
{
firstPage.clickAddAdditionalDetail();
String parentWindow=driver.getWindowHandle();
String childWin1="";
String childWin2="";
Set<String> windows=driver.getWindowHandles();
Iterator<String> iterator=windows.iterator();
childWin1=iterator.next();
driver.switchTo.window(childWin1);
firstPage.clickOneTimeDetail();// able to click this on second window, this click opens third window
Thread.sleep(3000);
childWin1=driver.getWindowHandle();
windows=driver.getWindowHandles();
childWin2=iterator.next();
driver.switchTo.window(childWin2);
// the third window is opened but driver control is not getting passed i think. even when i print all window ids it is printing same id for all parent and child
addDetailPage.enterFirstName(String fname);
}

【问题讨论】:

    标签: java selenium selenium-webdriver iterator set


    【解决方案1】:

    问题

    问题一:

    集合的迭代器,即使它是一个未排序的哈希集。 iterator.next() 从迭代器对象中随机返回元素,直到迭代器大小变为零。所以它不应该用于切换窗口逻辑,因为你不会总是得到你想要的元素。

    仅当您想以任意顺序遍历所有窗口时才使用它。

    问题二

    在每个元素输出迭代器从内存中删除元素并减小迭代器大小之后。

    因此,如果您有一组大小为 1 的集合,并且您尝试调用 iterator.next() 两次,它将抛出元素未找到,因为在第一个 next() 大小为 0 之后。第二个 next() 您正在尝试在大小减小时从大小为零的迭代器中获取元素

    在您的代码中

    您实际上是在执行以下逻辑。

    Set < String > hash_Set = new HashSet < String > ();
    
    hash_Set.add("Geeks");
    
    
    Iterator a = hash_Set.iterator();
    
    System.out.println(a.next());
    
    hash_Set
        = new HashSet < String > ();
    
    hash_Set.add("1");
    hash_Set.add("2");
    
    
    System.out.println(a.next());
    

    如果您运行此代码,您将收到一条错误消息,指出第二个 a.next() 没有此类元素。

    这是因为当您创建迭代器时 hash_set 只有一个元素。这会创建一个大小为 1 的迭代器。在第一个 .next() 中,它会删除一个元素并将大小设为零。

    即使在将 hash_set 更新为两个元素之后,迭代器也不会重新初始化。因此当您调用 a.next() 时,它会尝试从大小为“0”的迭代器中查找某些内容。 p>

    解决方案

    使用:

        Set<String> handlesSet = driver.getWindowHandles();
        Object[] handles = handlesSet.toArray();        
        childWin1=handles[handles.length-1];
    

    还要确保你打电话:

        handlesSet = driver.getWindowHandles();
        handles = handlesSet.toArray();     
        childWin2=handles[handles.length-1];
    

    每次打开新窗口时,您都会重新初始化数组。

    【讨论】:

      猜你喜欢
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多