問題描述
出于自動化目的,我正在創建一個在表格中查找行的腳本.此行是可點擊的,并打開一個新的選項卡/地址.
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 將焦點切換到選項卡,單擊鏈接后打開的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!