selenium web driver – 切换到父窗口

我使用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); 

但这不起作用。

在单击打开新窗口的链接之前尝试此操作:

 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 

public boolean switchBackParentWindowTitle(String windowTitle){

  boolean executedActionStatus = false; try { Thread.sleep(1000); WebDriver popup = null; Set handles = null; handles =driver.getWindowHandles(); Iterator 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; }