硒中的目标窗口已关闭

Man*_*h B 4 java testng selenium-webdriver

在所附的屏幕截图中,我要单击“新建浏览器窗口”。我想关闭浏览器窗口,然后单击“新消息”窗口。我关闭了浏览器窗口。但是我得到了例外

org.openqa.selenium.NoSuchWindowException: no such window: target window already closed
Run Code Online (Sandbox Code Playgroud)

屏幕截图

下面是详细信息 屏幕截图

下面是代码

@Test
public void testing()
{
    driver.manage().window().maximize();
    driver.get("http://www.seleniumframework.com/Practiceform/");
    driver.findElement(By.id("button1")).click();
    Set<String> handle=driver.getWindowHandles();
    for(String handles:handle){
       try{
          String text=driver.switchTo().window(handles).getPageSource();
          if(text.contains("Agile Testing and ATDD Automation")){
              System.out.println("Text found");
              driver.close();
              break;
          }
       }catch(Exception e){}
    }
    driver.switchTo().defaultContent();
    driver.findElement(By.xpath("//button[contains(text(),'New Message Window')]")).click();
    driver.quit();
Run Code Online (Sandbox Code Playgroud)

kot*_*toj 8

我想您尝试使用返回到原始窗口driver.switchTo().defaultContent();?这不是正确的方法。

你应该:

  1. 在测试开始时存储原始窗口:

String winHandleBefore = driver.getWindowHandle();

  1. 单击按钮,切换窗口,执行任何操作

  2. 要返回原始窗口,请使用:

driver.switchTo().window(winHandleBefore);

答案基于:https : //stackoverflow.com/a/9597714/4855333