Selenium等待加载Ajax内容 – 通用方法

是否有一种通用的方法让Selenium等到所有ajax内容都加载完毕? (不依赖于特定的网站 – 所以它适用于每个ajax网站)

你需要等待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 jQueryLoad = new ExpectedCondition() { @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 jsLoad = new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { return ((JavascriptExecutor)getDriver()).executeScript("return document.readyState") .toString().equals("complete"); } }; return wait.until(jQueryLoad) && wait.until(jsLoad); } 

正如Mark Collin在他的书“Mastering Selenium Webdriver”中所描述的那样,使用JavascriptExecutor让你弄清楚使用jQuery的网站是否已经完成了AJAX调用

 public class AdditionalConditions { public static ExpectedCondition jQueryAJAXCallsHaveCompleted() { return new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { return (Boolean) ((JavascriptExecutor) driver).executeScript("return (window.jQuery != null) && (jQuery.active === 0);"); } }; } } 

我不相信开箱即用的通用方法。 我通常会创建一个方法来执行轮询元素的.waituntilrowcount(2).waituntilrowcount(2)