小编典典

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

selenium

Selenium是否有一种通用方法可以等待所有ajax内容加载完毕?(不绑定到特定网站-因此它适用于每个ajax网站)


阅读 841

收藏
2020-06-26

共1个答案

小编典典

您需要等待Javascript和jQuery完成加载。执行Javascript来检查jQuery.activeis
0document.readyStateis 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);
}
2020-06-26