我的代码类似
WebDriver driver = new FirefoxDriver();
driver.get(something URL);
WebDriverWait waiting = new WebDriverWait(driver, 10, 1000);
WebElement element = waiting.until(ExpectedConditions.presenceOfElementLocated(By.id(my_id)));//problem is here
然后我尝试在我的页面上找到元素,WebDriverWait等到页面完全加载然后开始搜索。 如果我正在尝试这样的事情
WebDriverWait waiting = new WebDriverWait(driver, 10, 2700);
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
WebElement element;
try {
driver.get(something_url);
} catch (TimeoutException e) {
((JavascriptExecutor) driver).executeScript("window.stop();");
}finally {
element = waiting.until(ExpectedConditions.presenceOfElementLocated(By.id(my_id)));
}
它有效,但如果我继续这样下去
element.click();//go to another page
在这一行上不会抛出超时异常,我必须等待整页加载。 如何在这种情况下?
答案 0 :(得分:1)
解决方法是等待在此页面上完成ajax刷新:
public void waitForAjaxRefresh() {
System.out.println("Waiting for Ajax Refresh");
try {
WebDriverWait wait = new WebDriverWait(driver,35);
final JavascriptExecutor javascript = (JavascriptExecutor) (driver instanceof JavascriptExecutor ? driver
: null);
wait.until(new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver d) {
boolean outcome = Boolean.parseBoolean(javascript
.executeScript("return jQuery.active == 0")
.toString());
return outcome;
}
});
} catch (TimeoutException ex) {
throw new TimeoutException("Timed out after "
+ 35
+ " seconds while waiting for Ajax to complete.");
} catch (WebDriverException e) {
System.out.println("JQuery libraries are not present on page "
+ driver.getCurrentUrl() + " - "
+ driver.getTitle());
}
}