【问题标题】:Handle TABs in Selenium在 Selenium 中处理 TAB
【发布时间】:2016-10-04 11:44:53
【问题描述】:

我正在尝试在两个选项卡之间切换,发现以下代码

 ArrayList<String> tabs2 = new ArrayList<String> (page.getWindowHandles());
     System.out.println(tabs2.size());
        page.switchTo().window(tabs2.get(1));
        page.close();
        page.switchTo().window(tabs2.get(0));

我对此有一个疑问。我的窗口是一样的,所以page.getWindowHandles() 只返回一个句柄。 tabs2.size 是 1,所以 page.switchTo().window(tabs2.get(1)); 给出异常 ArrayIndexOutOfBound

我在这篇帖子switch tabs using Selenium WebDriver with Java 中找到了类似的代码,但对我来说,这段代码给出了异常。

【问题讨论】:

  • 这里有什么问题?如果您只有 1 个选项卡,那么您已经在该选项卡上......并且tabs2.size() 正在返回 1,这是正确的。
  • 我打开了两个标签,然后我使用这段代码仍然返回 1。那么如何在两个标签上工作?
  • 您是使用selenium 还是手动打开第二个选项卡,还是应用程序行为?
  • 我使用了这个代码 page.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

标签: java selenium selenium-webdriver


【解决方案1】:

只需尝试添加一行代码,以确保浏览器中打开了两个或更多选项卡:

page.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

请注意,要发送的实际密钥取决于您的操作系统,例如 Mac 使用Keys.COMMAND + t,而不是Keys.CONTROL + t

发布这个,你使用的这段代码似乎适合切换标签:

ArrayList<String> tabs2 = new ArrayList<String> (page.getWindowHandles());
System.out.println(tabs2.size());
page.switchTo().window(tabs2.get(1));
page.close();
page.switchTo().window(tabs2.get(0));

注意:我假设这里的页面是 WebDriver 实例本身。

【讨论】:

  • 是的,谢谢亲爱的,我是stackoverflow的新手,所以下次不会犯这个错误。我在 Firefox 中打开新标签,我的代码仅适用于 Firefox
【解决方案2】:
protected void switchTabsUsingPartOfUrl(String platform) {
        String currentHandle = null;
        try {
            final Set<String> handles = driver.getWindowHandles();
            if (handles.size() > 1) {
                currentHandle = driver.getWindowHandle();
            }
            if (currentHandle != null) {
                for (final String handle : handles) {
                    driver.switchTo().window(handle);
                    if (currentUrl().contains(platform) && !currentHandle.equals(handle)) {
                        break;
                    }
                }
            } else {
                for (final String handle : handles) {
                    driver.switchTo().window(handle);
                    if (currentUrl().contains(platform)) {
                        break;
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Switching tabs failed");
        }
    }

调用该方法并传递参数一个你要切换到的标签的url子串

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-01
    • 2017-07-03
    • 2021-11-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多