如何利用Selenium中的索引切换到窗口 [英] How to switch into Window using Index in Selenium

查看:74
本文介绍了如何利用Selenium中的索引切换到窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为Selenium没有提供切换到窗口(多个窗口)的方法,但是我想做一个自定义的方法来使用索引切换到不同的窗口。但是下面的代码没有按照预期工作。请建议以下方法的最佳实施。

    public void switchToWindowIndex(int index) {
    Set<String> windows = driver.getWindowHandles();
    int totalWin = windows.size();
    String winTitle = null;
    for (int i =0; i<= totalWin; i++) {
        if (i == index) {
            winTitle = windows.toArray()[i].toString();
            return;
        }
        System.out.println(windows.toArray()[i].toString());

    }
    driver.switchTo().window(winTitle);
    logger.info("Switched to " + driver.getTitle());
}

提前感谢。

推荐答案

使用Selenium时,不应窗口句柄之间使用索引,因为虽然看起来窗口句柄的排序方式是先排序最旧的窗口,最后排序最新的窗口。但事实并非如此:它完全是随机的!

在一次讨论中,Simon明确提到:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.

因此,要在窗口句柄之间切换,您必须使用以下任一选项:

这篇关于如何利用Selenium中的索引切换到窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆