Selenium Webdriver – 等待页面完全加载Java和JavaScript(ajax / jquery / animation等)

我正在尝试构建一个更好的方法来等待每次单击后加载页面。 目前我用过的是:

public boolean waitForJSandJQueryToLoad() { WebDriverWait wait = new WebDriverWait(webDriver, EnvironmentUtils.getPageLoadTimeout().intValue()); // wait for jQuery to load ExpectedCondition jQueryLoad = new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { try { if (!((Boolean) callJS("return (window.jQuery != null) && (jQuery.active === 0);"))) { log.info("JQUERY.ACTIVE IS WORKING AT THE MOMENT! jQuery.active= " + callJS("return jQuery.active")); } return (Boolean) callJS("return (window.jQuery != null) && (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) { if (!callJS("return document.readyState").toString().equals("complete")) { log.info("document.readyState is not complete at the moment! status is->" + callJS("return document.readyState").toString()); } return callJS("return document.readyState").toString().equals("complete"); } }; ExpectedCondition animationLoad = new ExpectedCondition() { @Override public Boolean apply(WebDriver driver) { if (!callJS("return $(\":animated\").length").toString().equals("0")) { log.info("Animation is currently executing on-page. value ->" + callJS("return $(\":animated\").length").toString()); } return callJS("return $(\":animated\").length").toString().equals("0"); } }; return wait.until(jQueryLoad) && wait.until(jsLoad) && wait.until(animationLoad); } 

在某些情况下,单击某个按钮并等待表后加载但我运行countRowsInTable方法(通过selenium命令计算表中的行数)时,我的测试仍然失败,它会显示零,而实际视觉效果根本不为零,count行的命令工作正常,如果要检查它,这是代码:

 public int countDisplayedRowsInTable(String tableId) { waitForJSandJQueryToLoad(); int count = 0; List rows = webDriver.findElements(By.xpath("//table[@id='" + tableId + "']/tbody/tr")); for (WebElement row : rows) { if (row.isDisplayed()) count++; } return count; } 

我很确定我用waitForJSandJQueryToLoad方法覆盖任何东西,我希望你可以给我一些额外的声明,也许我错过了。 提前致谢。

我认为您可以定义一个显式等待,等待某个条件发生,然后再继续执行代码。

  public int countDisplayedRowsInTable(String tableId) { String e = "//table[@id='" + tableId + "']"; // Wait for the table to load WebElement table = (new WebDriverWait(driver, intCustomWait)) .until(ExpectedConditions.elementToBeClickable(By.xpath(e)); // Get all the rows from within the table List rows = table.findElements(By.xpath("./tbody/tr")); if(rows.size() > 0) { int count = 0; for (WebElement row : rows) { if (row.isDisplayed()) count++; } return count; } else return -1; }