Selenium是否有一种通用方法可以等待所有ajax内容加载完毕?(不绑定到特定网站-因此它适用于每个ajax网站)
您需要等待Javascript和jQuery完成加载。执行Javascript来检查jQuery.activeis 0和document.readyStateis complete,这意味着JS和jQuery加载已完成。
jQuery.active
0
document.readyState
complete
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); }