2017-07-04 93 views
1

在我的網站,當我在主頁上搜索任何東西它的開放一個葉窗和一個隱藏彈出式背後 window.Using硒我想正確或不知道它的開放,也藉此兩個窗口鏈接。硒獲取彈出和隱藏彈出式當前打開的鏈接

我試過,但它不工作

public class Utility 
{ 
    public static WebDriver getHandleToWindow(String title){ 

     //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle. 
     WebDriver popup = null; 
     Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles(); 
     System.err.println("No of windows : " + windowIterator.size()); 
     for (String s : windowIterator) { 
      String windowHandle = s; 
      popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle); 
      System.out.println("Window Title : " + popup.getTitle()); 
      System.out.println("Window Url : " + popup.getCurrentUrl()); 
      if (popup.getTitle().equals(title)){ 
       System.out.println("Selected Window Title : " + popup.getTitle()); 
       return popup; 
      } 

     } 
       System.out.println("Window Title :" + popup.getTitle()); 
       System.out.println(); 
      return popup; 
     } 
} 

回答

2

當你推出只有一個webdriver的過程中,將只有一個的webdriver。它包含一個窗口句柄列表。你不需要有多個WebDriver實例。如果您想要轉到新窗口(或選項卡)然後返回主窗口,則應在WebDriverInitialize類的某處存儲主窗口的窗口句柄。我下面的例子展示瞭如何將windowHandle存儲在Utility類中。

public class Utility 
{ 
    public static void switchToNewWindow(String title){ 
     Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles(); 
     System.err.println("No of windows : " + windowIterator.size()); 
     for (String s : windowIterator) { 
      String windowHandle = s; 
      WebDriverInitialize.getDriver().switchTo().window(windowHandle); 
      System.out.println("Window Title : " + WebDriverInitialize.getDriver().getTitle()); 
      System.out.println("Window Url : " + WebDriverInitialize.getDriver().getCurrentUrl()); 
      // you may use .getTitle().contains(title) if you cannot predict the full title 
      if (WebDriverInitialize.getDriver().getTitle().equals(title)){ 
       break; 
      } 
     } 
    } 

    public static string mainWindowHandle; 

} 

WebDriverInitialize.getDriver().get("https://www.rentalhomes.com/"); 
Utility.mainWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); 
... 
WebDriverInitialize.getDriver().findElement(By.id("home-page-search-btn")).click(); 
// Switch to the new window 
Utility.switchToNewWindow("San Francisco ..."); 
// Switch back to main window 
WebDriverInitialize.getDriver().switchTo().window(Utility.mainWindowHandle); 
+0

WebDriverInitialize這個代碼庫的問題。你建議我該如何解決。 – zsbappa

+0

@zsbappa你能顯示錯誤嗎? – Buaban