java - 等待图像完全加载 Selenium WebDriver

标签 java selenium selenium-webdriver webdriver

我看到有个问题:Selenium-Webdriver Ruby --> How to wait for images to be fully loaded after click

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

  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;
      }
    };
  }

但如果图像已经有高度和宽度,即使图像尚未加载,它也可能被视为可见

最佳答案

您可以执行一些 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:

Returns a Boolean that is true if the browser has finished fetching the image, whether successful or not. It also shows true, if the image has no src value.

关于java - 等待图像完全加载 Selenium WebDriver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42655802/

相关文章:

java - 在 Flume 生命周期中使用 Spring AMQP onMessage() 方法

java - 在 javafx 中首先控制获取焦点

java - 获取错误 : org. openqa.selenium.WebDriverException:未知错误:键应该是一个字符串

java - JButton isselected 方法不起作用

node.js - 在 Nightwatch.js 命令中使用 XPath 来选择 Polymer Element 的子元素?

python - 如何在 html 中单击 zebra datepicker 中的日期?

python - 如何通过 Selenium 根据 url 将文本发送到地理位置搜索框

javascript - Chrome 的 AutoSelectCertificateForUrls 仅在非 headless 模式下工作

java - Selenium-Java-Actions 类型错误 : rect is undefined

java - 如何使用JAVA访问Hadoop MapReduce中Iterable <DoubleWritable>的第一个元素?