-1

我正在使用 Java 和 Selenium 来自动化一些测试用例。这涉及加载带有搜索结果的单个页面并遍历该单个页面上的每 100-1000 个链接。将测试配置设置为仅检查大约 100 个结果通常是可以的,但任何高于此的结果都会引发 NoSuchWindowException(WebDriverException 的子类)。当我从父句柄切换到新打开的窗口句柄时会发生这种情况。

我已经在 do while 循环中编写了一个 try-catch 语句来捕获异常并重试该过程......但是,无论我尝试什么,Selenium 都不会很好,并且我的代码执行突然结束...... :( 这是代码:

boolean completed = false;
    do{
        try{
            //click the search result
            driver.findElement(By.xpath("my xpath string")).click();
            //switch to the new window
            for(String winHandle: driver.getWindowHandles()){
                driver.switchTo().window(winHandle);
            }
            //for our test we need to save the source       
            source = driver.getPageSource();
            //close popup window and and switch back to the parent handle
            driver.close();
            driver.switchTo().window(parentHandle);
            completed = true;
        }catch(WebDriverException ex){
            System.out.println("something went wrong while switching windows... retrying");
            driver.close();
            driver.switchTo().window(parentHandle);
        }
    }while(!completed);

当捕获到异常时,我尝试了各种方法。例如,我尝试使用 driver.quit() 保存父 url,然后尝试重新启动驱动程序。但是,然后 Selenium 抱怨我在调用 driver.quit() 后无法启动 Firefox 驱动程序...

任何想法如何更好地处理我的代码的捕获部分?

4

1 回答 1

0

好的,感谢 Tala 留下的评论,我找到了解决方案。

我只是从 catch 块中删除了以下语句:

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

现在,catch 块本身不会生成单独的未捕获异常,并且循环可以正确地重试之前的代码......

于 2013-08-07T13:54:12.677 回答