25

我使用 Selenium WebDriver。我打开第一页然后打开第二页 - 执行一些操作并返回第一页。在我想关闭第二页之前,我使用 command driver.close();,但它关闭了第一页而不是第二页。如何让 Selenium 关闭特定窗口?

部分代码

String HandleBefore = driver.getWindowHandle();

 driver.findElement(By.xpath("...")).click();
 for (String twohandle : driver.getWindowHandles()) {
        driver.switchTo().window(twohandle);
    }       
 driver.findElement(By.linkText("001")).click();
 driver.close();
4

4 回答 4

25
    String base = driver.getWindowHandle();

    Set <String> set = driver.getWindowHandles();

    set.remove(base);
    assert set.size()==1;

    driver.switchTo().window(set.toArray(new String[0]));

    driver.close();
    driver.switchTo().window(base);

这对我有用...

于 2012-07-12T10:13:56.297 回答
11

在 Python 中

default_handle = driver.current_window_handle
handles = list(driver.window_handles)
assert len(handles) > 1

handles.remove(default_handle)
assert len(handles) > 0

driver.switch_to_window(handles[0])
# do your stuffs
driver.close()
driver.switch_to_window(default_handle)
于 2016-03-01T09:33:12.460 回答
2

您可以通过标题或标识该窗口的特定唯一元素来关闭特定窗口。

private void SwitchTabandClose()
{
    Set <String> windows = driver.getWindowHandles();
    String mainwindow = driver.getWindowHandle();

    for (String handle: windows)
    {
        driver.switchTo().window(handle);
        System.out.println("switched to "+driver.getTitle()+"  Window");
        String pagetitle = driver.getTitle();
        if(pagetitle.equalsIgnoreCase("XYZ Title"))
        {
            driver.close();
            System.out.println("Closed the  '"+pagetitle+"' Tab now ...");
        }
    }

    driver.switchTo().window(mainwindow);
 }
于 2016-02-15T14:24:14.880 回答
1

Ramnarayan 的解决方案效果很好。对其进行了一些修改以实现可重用性:

public static String switchToWindowByTitle(WebDriver driver, String windowTitle) {
  Set<String> handles = driver.getWindowHandles();
  String currentHandle = driver.getWindowHandle();
  for (String handle : handles) {
    driver.switchTo().window(handle);
    if (windowTitle.equalsIgnoreCase(driver.getTitle())) {
      break;
    }
  }

  return currentHandle;
}


// How to use method
String currentHandle = SeleniumUtil.switchToWindowByTitle(driver, WINDOW_TITLE);
driver.close(); // Close WINDOW_TITLE page or do other things
driver.switchTo().window(currentHandle); // Return to current page
于 2017-08-21T17:38:20.237 回答