2012-10-17 52 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的條件。