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 将焦点切换到选项卡,单击链接后打开
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01