如何关闭使用硒的webdriver与Java特定的窗口?(How can I close a spe

2019-06-26 05:20发布

我用硒的webdriver。 我打开第一页然后打开第二页 - 执行某些操作,并返回到第一页。 之前,我想关闭第二页我用命令driver.close(); ,但它关闭,而不是第二个第一页。 我怎样才能让硒关闭特定的窗口?

部分代码

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();

Answer 1:

    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);

这对我的作品...



Answer 2:

在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)


Answer 3:

你可以通过它的标题关闭特定窗口或标识窗口的具体独特的元素..

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);
 }


Answer 4:

Ramnarayan所述的解决方案的伟大工程。 修改有点为reusablity:

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


文章来源: How can I close a specific window using Selenium WebDriver with Java?