使用WebDriver单击新打开的选项卡中的链接 [英] Clicking links in newly opened tab using WebDriver

查看:154
本文介绍了使用WebDriver单击新打开的选项卡中的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在这种情况下帮助我:

Can someone please help me in this scenario:

情景是:有一个网页,我打开了所有指定的链接仅在新标签中。现在我想点击新打开的Tab中的任何一个链接。尝试下面,但它只是点击主/第一个标签中的一个链接,而不是在新标签中。

Scenario is: There is a webpage and I am opening all of my specified links in new Tab only. Now I am trying to click any one link in newly opened Tab. Tried below, but it is clicking that one link in the main/first tab only, instead of in new tab.

new Actions(driver).sendKeys(Keys.CONTROL).sendKeys(Keys.NUMPAD1).perform();
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL, Keys.TAB);
List<WebElement> links=driver.findElements(By.xpath("//a[contains(@href,'http')]"));
links.get(0).click();


推荐答案

您需要使用 .switchTo(windowHandle); 命令用于访问第二个选项卡。

You will need to use the .switchTo(windowHandle); command to access your second tab.

在打开第二个选项卡之前 - 获取打开选项卡的windowHandle:

Before opening the second tab - get the windowHandle of the open tab:

String mainWindow = driver.getWindowHandle();

然后执行打开第二个标签的操作。现在你需要知道第二个标签的句柄并将控制权切换到它:

Then do your action that opens the second tab. Now you'll need to know the handle of the second tab and switch control to it:

Set<String> handles = driver.getWindowHandles();  
for (String handle : handles) {
    if (!handle.equals(mainWindow)) {
          driver.switchTo().window(handle);
          break;
    }
}

您对第二个标签的操作现在将在第二个窗口。当你完成并需要再次与第一个标签交互时: driver.switchTo()。defaultContent();

Your actions for the second tab will now happen in that second window. When you're finished and need to interact with the first tab again: driver.switchTo().defaultContent();

这篇关于使用WebDriver单击新打开的选项卡中的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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