我正在使用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);
当发现异常时,我尝试了各种方法。例如,我尝试保存父URL,使用driver.quit(),然后尝试重新启动驱动程序。然而,Selenium抱怨说我在调用driver.quit()之后无法启动Firefox驱动程序......
如何更好地处理代码中的catch部分?
答案 0 :(得分:0)
好的,我已经找到了解决方案,感谢Tala留下的评论。
我只是从catch块中删除了以下语句:
driver.close();
driver.switchTo().window(parentHandle);
现在catch块本身并没有生成一个单独的未捕获异常,并且循环正确地重复执行以前的代码...