如何透過 Selenium 來處理彈出視窗?
Selenium 提供 getWindowHandles() 方法,它返回所有開啟的視窗的所有視窗控制代碼 ID。這些 ID 儲存在字串資料型別的資料結構 Set 中。
為了導航到特定視窗,我們需透過 iterator() 方法遍歷需要訪問的視窗,然後切換到該視窗。
getWindowHandle() 方法返回當前視窗 ID 的視窗控制代碼 ID。
示例
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; import java.util.Set; import java.util.Iterator; import org.testng.annotations.Test; public class WindowHandles{ @Test public void windowHandle() throws Exception { System.setProperty("webdriver.chrome.driver", "C:\Selenium\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://tutorialspoint.tw/index.htm"); // getting the current window handle id String currentwindow = driver.getWindowHandle(); // getting all the window handles in Set data structure Set<String> allWindows = driver.getWindowHandles(); // traversing each ids with the help of iterator() Iterator<String> i = allWindows.iterator(); //Iterating through the window handle ids while(i.hasNext()){ String childwindow = i.next(); if(!childwindow.equalsIgnoreCase(currentWindow)){ driver.switchTo().window(childwindow); System.out.println("The child window is "+childwindow); } else { System.out.println("There are no children"); } } driver.quit(); } }
廣告