Clicking links in newly opened tab using WebDriver

2020-06-23 06:50发布

Can someone please help me in this scenario:

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();

1条回答
何必那么认真
2楼-- · 2020-06-23 07:46

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

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;
    }
}

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();

查看更多
登录 后发表回答