你可以做這樣的事情:
System.out.println("before wait");
WebElement el = (new WebDriverWait(driver, 30))
.until(new ExpectedCondition<WebElement>(){
//try the following cycle for 30 seconds
@Override
public WebElement apply(WebDriver driver) {
//refresh the page
driver.navigate().refresh();
System.out.println("Refreshed");
//look for element for 5 seconds
WebElement sameElement = null;
try{
sameElement = (new WebDriverWait(driver, 5))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver driver) {
System.out.println("Looking for the element");
return driver.findElement(By.id("theElementYouAreLookingFor"));
}});
} catch (TimeoutException e){
// if NULL is returns the cycle starts again
return sameElement;
}
return sameElement;
}});
System.out.println("Done");
它將嘗試獲取元素30秒,刷新頁面每隔5秒。
爲什麼你不會刷新然後等待元素?爲什麼在等待期間你必須刷新**? –
嗯,我在等待之前做了一個刷新,但是元素可能不會在那裏,在這種情況下它會失敗,因爲不管我等多久,除非我再次刷新元素都不會出現。我想我可以把等待放在一個循環中,這樣我可以刷新並等待幾次。 –
所以你必須刷新多次?你有刷新的限制嗎? (數量或時間) –