如何通过 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.com/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();
   }
}

更新于: 10-Jun-2020

2K+ 浏览量

开始你的 事业

通过完成课程获得认证

开始
广告