Selenium switch focus to tab, which opened after clicking link(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 将焦点切换到选项卡,单击链接后打开
基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01