等待图片完全加载 Selenium WebDriver

6
我看到有一个问题:Selenium-Webdriver Ruby --> 如何在单击后等待图像完全加载

但似乎没有人直接回答:我需要等待图像完全加载,而不仅仅是出现在DOM中,使用selenium WebDriver。我该怎么办?目前我正在使用

  public static void waitUntilVisible(WebDriver webDriver, By locator) {
    WebDriverWait driverWait = new WebDriverWait(webDriver, TIMEOUT);
    driverWait.until(visibilityOfElementLocated(locator));
  }

这使用了

  /**
   * An expectation for checking that an element is present on the DOM of a page and visible.
   * Visibility means that the element is not only displayed but also has a height and width that is
   * greater than 0.
   *
   * @param locator used to find the element
   * @return the WebElement once it is located and visible
   */
  public static ExpectedCondition<WebElement> visibilityOfElementLocated(
    final By locator) {
    return new ExpectedCondition<WebElement>() {
      @Override
      public WebElement apply(WebDriver driver) {
        try {
          return elementIfVisible(findElement(locator, driver));
        } catch (StaleElementReferenceException e) {
          return null;
        }
      }

      @Override
      public String toString() {
        return "visibility of element located by " + locator;
      }
    };
  }

但是,如果一张图片已经有了高度和宽度,即使图片没有加载完成,它可能被视为可见。


你找到答案了吗? - st0ve
1个回答

8

您可以执行一些JavaScript来查询DOM。具体来说,是HTMLImageElementcomplete属性。

public static void waitUntilVisible(WebDriver webDriver, By locator) {
    WebDriverWait driverWait = new WebDriverWait(webDriver, TIMEOUT);
    WebElement el = webDriver.findElement(locator);
    driverWait.until(
        new Predicate<WebDriver>() {
            public boolean apply(WebDriver driver) {
                return ((JavascriptExecutor)driver).executeScript("return arguments[0].complete", el);
            }
        }
    );
}

但需要注意的是complete属性:

complete属性返回一个布尔值,如果浏览器已经完成获取图像,无论成功与否,它都为true。如果图像没有src值,则也会返回true。


我想指出,在C#中,该方法返回一个带有单词“false”或“true”的字符串,具体视图像状态而定,只需在返回之前解析为布尔值,否则它将无法正常工作。 - ManoPajaro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接