selenium-切換到新的窗口

/**
  * 功能: 切換windows窗口
  *@param driver
  *@param windowTitle
  *@return boolean
  */
 public boolean switchToNewWindow(WebDriver driver, String windowTitle) {
  boolean flag = false;
  try {
   String currentHandle = driver.getWindowHandle();
   Set<String> handles = driver.getWindowHandles();
   for (String s : handles) {
    if (s.equals(currentHandle))
     continue;
    else {
     driver.switchTo().window(s);
     if (driver.getTitle().contains(windowTitle)) {
      flag = true;
      System.out.println("Switch to window: " + windowTitle
        + " successfully!");
      break;
     } else
      continue;
    }
   }
  } catch (NoSuchWindowException e) {
   System.out.println("Switch to window: " + windowTitle
     + " failed!");
   e.printStackTrace();
   flag = false;
  }
  return flag;
 }
 
 /**
  * 功能:刪除一個窗口的Handler,因爲set集合是無序的,因此須要刪除 
  *@param driver
  *@param firstHandler
  */
 public void removeOldWindow(WebDriver driver, String firstHandler) {
  
  // 獲取全部窗口的Handler,並存放在Set集合裏
  Set<String> handlers = driver.getWindowHandles();windows

  // 刪掉第一個窗口的Handler
  if (handlers.remove(firstHandler)) {
   System.out.println("已刪掉第一個窗口的Handler");
  }
  
  // 把Set集合轉換成Iterator
  Iterator<String> it = handlers.iterator();
  try {
   if (it.hasNext()) {
    driver.switchTo().window(it.next());
   }
  } catch (Exception e) {
   System.out.println("沒有可用的窗口Handler");
  }
 }rem

相關文章
相關標籤/搜索