Selenium 将焦点切换到选项卡,单击链接后打开

Selenium switch focus to tab, which opened after clicking link(Selenium 将焦点切换到选项卡,单击链接后打开)

本文介绍了Selenium 将焦点切换到选项卡,单击链接后打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于自动化目的,我正在创建一个在表格中查找行的脚本.此行是可点击的,并打开一个新的选项卡/地址.

For automation purposes, I am working on creating a script that finds a row in a table. This row is clickable and opens a new tab/adress.

使用 selenium,我现在可以找到表格行,单击链接,然后打开新选项卡.问题是我找不到任何方法将焦点切换到新打开的选项卡.我试图获取所有 windowHandle 并查看是否可以切换,但即使在新选项卡打开后,也只有 1 个 windowHandle.

With selenium, I am now able to find the table row, click on the link, and the new tab opens. The problem is that I can't find any way to switch the focus to the newly opened tab. I tried to get all windowHandles and see if I could switch, but even after the new tab has opened, there is only 1 windowHandle.

下面是我的代码:

WebElement tableRow=driver.findElement(By.xpath("/html/body/div[1]/table/tbody/tr[2]"));

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", tableRow);

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
    }

Arraylist 始终包含 1 个单个 windowHandle,而不是 2 个.所以我无法将焦点切换到新选项卡.有没有办法解决这个问题?

The Arraylist always contains 1 single windowHandle, not 2. So I am not able to switch focus to the new tab. Is there any way to solve this?

推荐答案

要正确切换到新打开的 Tab 你需要为 New 诱导 WebDriverWaitTab 进行渲染,然后通过 for() 循环,您需要遍历可用的 WindowHandles 并调用 switchTo().window()WindowHandle 不是通过以下代码块的前一个 TAB :

To properly switch to the newly opened Tab you need to induce WebDriverWait for the New Tab to render and then through a for() loop you need to iterate through the available WindowHandles and invoke switchTo().window() with the WindowHandle which is not the previous TAB through the following code block :

String first_handle = driver.getWindowHandle();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", tableRow);
new WebDriverWait(driver,5).until(ExpectedConditions.numberOfWindowsToBe(2));
Set<String> allHandles = driver.getWindowHandles();
for(String winHandle:allHandles)
{
    if (!first_handle.equalsIgnoreCase(winHandle)
    {
        driver.switchTo().window(winHandle);
    }
}

这篇关于Selenium 将焦点切换到选项卡,单击链接后打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Selenium 将焦点切换到选项卡,单击链接后打开

基础教程推荐