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

查看:54
本文介绍了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,我现在可以找到表格行,单击链接,然后打开新选项卡.问题是我找不到任何方法将焦点切换到新打开的选项卡.我试图获取所有 windowHandles 并查看是否可以切换,但即使在新选项卡打开后,也只有 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 将焦点切换到选项卡,点击链接后打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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