Selenium是否有通用方法等待所有ajax内容加载? (不依赖于特定的网站 - 所以它适用于每个ajax网站)
答案 0 :(得分:24)
你需要等待Javascript和jQuery才能完成加载。执行Javascript以检查jQuery.active
是否为0
且document.readyState
为complete
,这意味着JS和jQuery加载已完成。
public boolean waitForJSandJQueryToLoad() {
WebDriverWait wait = new WebDriverWait(driver, 30);
// wait for jQuery to load
ExpectedCondition<Boolean> jQueryLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
try {
return ((Long)((JavascriptExecutor)getDriver()).executeScript("return jQuery.active") == 0);
}
catch (Exception e) {
// no jQuery present
return true;
}
}
};
// wait for Javascript to load
ExpectedCondition<Boolean> jsLoad = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)getDriver()).executeScript("return document.readyState")
.toString().equals("complete");
}
};
return wait.until(jQueryLoad) && wait.until(jsLoad);
}
答案 1 :(得分:2)
正如Mark Collin在他的书“Mastering Selenium Webdriver”中所描述的那样,使用JavascriptExecutor让你弄清楚使用jQuery的网站是否已经完成了AJAX调用
public class AdditionalConditions {
public static ExpectedCondition<Boolean> jQueryAJAXCallsHaveCompleted() {
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
return (Boolean) ((JavascriptExecutor) driver).executeScript("return (window.jQuery != null) && (jQuery.active === 0);");
}
};
}
}
答案 2 :(得分:1)
我一直在使用这个简单的do进行迭代,直到完成AJAX。 它始终为我工作。
public void waitForAjax() throws InterruptedException{
while (true)
{
Boolean ajaxIsComplete = (Boolean) ((JavascriptExecutor)driver).executeScript("return jQuery.active == 0");
if (ajaxIsComplete){
info("Ajax Call completed. ");
break;
}
Thread.sleep(150);
}
}
答案 3 :(得分:0)
我不相信开箱即用的通用方法。我通常会创建一个方法来执行轮询元素的.waituntilrowcount(2)
或waituntilvisible()
。