2012-07-06 65 views
0

我使用硒Web驅動程序。我打開了一個父窗口。點擊鏈接後,新窗口打開。我從列表中選擇一些值,並自動關閉此窗口。現在我需要在我的父窗口中操作。我怎樣才能做到這一點?我試了下面的代碼:selenium web driver - 切換到父窗口

String HandleBefore = driver.getWindowHandle(); 
driver.findElement(By.xpath("...")).click(); 
for (String Handle : driver.getWindowHandles()) { 
     driver.switchTo().window(Handle);} 
driver.findElement(By.linkText("...")).click(); 
driver.switchTo().window(HandleBefore); 

雖然這不起作用。

+0

您遍歷打開的窗口切換到大家,並在結束你繼續在列表中的最後....那是什麼? – 2012-07-06 09:07:31

+0

我只是不知道另一種方式切換到子窗口。它適用於我,但我不能切換回父 – khris 2012-07-06 09:16:58

回答

1

試試這個你點擊打開的新窗口中的鏈接之前:

parent_h = browser.current_window 
# click on the link that opens a new window 
handles = browser.window_handles # before the pop-up window closes 
handles.remove(parent_h) 
browser.switch_to_window(handles.pop()) 
# do stuff in the popup 
# popup window closes 
browser.switch_to_window(parent_h) 
# and you're back 
+0

我知道這是在python中......但你可以將方法轉換成java – 2012-07-10 04:44:51

0

公共布爾switchBackParentWindowTitle(字符串WINDOWTITLE){

boolean executedActionStatus = false; 
    try { 

     Thread.sleep(1000); 
     WebDriver popup = null; 
     Set<String> handles = null; 

     handles =driver.getWindowHandles(); 
     Iterator<String> it = handles.iterator(); 
     while (it.hasNext()){ 

      String switchWin = it.next(); 
      popup = driver.switchTo().window(switchWin); 

      System.out.println(popup.getTitle()); 
      if(popup.getTitle().equalsIgnoreCase(windowTitle)){ 

       log.info("Current switched window title is "+popup.getTitle()); 
       log.info("Time taken to switch window is "+sw.elapsedTime()); 
       executedActionStatus = true; 
       break; 
      } 
      else 
       log.info("WindowTitle does not found to switch over"); 
     } 
    } 
    catch (Exception er) { 
     er.printStackTrace(); 
     log.error("Ex: "+er); 
    } 
    return executedActionStatus; 
} 
相關問題