Selenium 里`getWindowHandle()` 和 `getWindowHandles()` 有什么不同?
`getWindowHandle()` 和 `getWindowHandles()` 方法有一些突出的差异。
`driver.getWindowHandles()` – 存储多个同时打开的页面句柄的集合。
`driver.getWindowHandle()` – 获取处于焦点状态的网页的句柄。它获取活动浏览器的地址,返回类型为字符串。
代码实现
范例
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.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.com/index.htm"); String currentwindow = driver.getWindowHandle(); Set<String> allWindows = driver.getWindowHandles(); Iterator<String> i = allWindows.iterator(); 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(); } }
广告