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

Fab*_*urz 19 java selenium web-crawler selenium-webdriver

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

LIN*_*NGS 25

你需要等待Javascript和jQuery才能完成加载.执行JavaScript,以检查是否jQuery.active0document.readyStatecomplete,这意味着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);
}
Run Code Online (Sandbox Code Playgroud)