2012-10-17 48 views
2

我正在使用Selenium WebDriver和Java编写自动化测试,需要在其中进行大量等待以确保在执行下一个操作之前加载了相应的元素。Selenium Webdriver/Java-等待函数和错误处理

我已经试过这样:

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); 

将等待指定的时间间隔,然后如果没有找到该元素,失败,

这:

WebDriverWait wait = new WebDriverWait(driver, 100); 
wait.until(new ExpectedCondition<Boolean>() { 
    public Boolean apply(WebDriver webDriver) { 
    System.out.println("Searching for the Companies dropdown"); 
    return webDriver.findElement(By.id("ctl00_PageContent_vpccompanies_Input")) != null; 
    } 
}); 

这将如果找不到元素,则无限期挂起,

我想要的是会搜索h为元素进行了几次尝试,然后失败并显示错误消息。

+0

你不满意答案吗?请接受答案。 –

回答

0

我会说,把your element access code放在一个while循环中,它在successnumber of attempts上打破。

例如(伪代码)

int numAttemps = 0; 
    int specifiedAttempts = 5; 
    boolean success = false; 
    do{ 
     numAttemps++; 
     try{ 
     //access the element 
      WebElement element = driver.findElement(By.id(..)); 
      success = true; //<--If it reaches here means success 
     }catch(NoSuchElementException nse) 
      //one attempt failed 
     } 
    }while(!success || numAttemps <specifiedAttempts); 

    if(!success){ 
     System.out.println("Couldn't load after " +specifiedAttempts+ " attempts"); 
    } 
+0

谢谢,这很有帮助! –

1

包装你的代码到一个周期,循环,直到匹配查找条件或附加条件,即退出循环。 使用isElementPresent(element)检查find的条件。