How can I close a specific window using Selenium WebDriver with Java?

后端 未结 4 761
耶瑟儿~
耶瑟儿~ 2021-01-03 21:27

I use Selenium WebDriver. I open the first page then open the second page - perform some action and go back to first page. Before I want to close the second page I use the c

相关标签:
4条回答
  • 2021-01-03 22:08

    In 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)
    
    0 讨论(0)
  • 2021-01-03 22:08

    Ramnarayan's solution works great. Modified it a bit for 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
    
    0 讨论(0)
  • 2021-01-03 22:17
        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);
    

    This works for me...

    0 讨论(0)
  • 2021-01-03 22:17

    You can close a specific window by it's title or identifying a specific unique element of that window..

    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);
     }
    
    0 讨论(0)
提交回复
热议问题