使用 Selenium WebDriver 和 Java 切换选项卡

新手上路,请多包涵

在 Java 中使用 Selenium WebDriver。我正在尝试自动化一项功能,在该功能中我必须打开一个新选项卡并在那里执行一些操作并返回上一个选项卡(父级)。我使用了开关手柄,但它不起作用。一件奇怪的事情是两个选项卡具有相同的窗口句柄,因此我无法在选项卡之间切换。

但是,当我尝试使用不同的 Firefox 窗口时,它可以工作,但对于选项卡它不起作用。

如何切换标签?或者,如何在不使用窗口句柄的情况下切换选项卡,因为在我的情况下,两个选项卡的窗口句柄相同?

(我观察到,当您在同一个窗口中打开不同的选项卡时,窗口句柄保持不变)

原文由 Umesh Kumar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答
    psdbComponent.clickDocumentLink();
    ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs2.get(1));
    driver.close();
    driver.switchTo().window(tabs2.get(0));

这段代码非常适合我。试试看。在你想在新标签上做某事之前,你总是需要将你的驱动程序切换到新标签。

原文由 Sireesha Middela 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个简单的解决方案,用于打开新选项卡、将焦点更改到它、关闭选项卡并将焦点返回到旧/原始选项卡:

 @Test
public void testTabs() {
    driver.get("https://business.twitter.com/start-advertising");
    assertStartAdvertising();

    // considering that there is only one tab opened in that point.
    String oldTab = driver.getWindowHandle();
    driver.findElement(By.linkText("Twitter Advertising Blog")).click();
    ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
    newTab.remove(oldTab);
    // change focus to new tab
    driver.switchTo().window(newTab.get(0));
    assertAdvertisingBlog();

    // Do what you want here, you are in the new tab

    driver.close();
    // change focus back to old tab
    driver.switchTo().window(oldTab);
    assertStartAdvertising();

    // Do what you want here, you are in the old tab
}

private void assertStartAdvertising() {
    assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}

private void assertAdvertisingBlog() {
    assertEquals("Twitter Advertising", driver.getTitle());
}

原文由 Jordan Silva 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题