2017-03-07 60 views
2

我看到有一个问题:Selenium-Webdriver Ruby --> How to wait for images to be fully loaded after click等待图像满载硒的webdriver

但似乎没有人直接回答说:我需要等待的图像满载,而不仅仅是在DOM中使用硒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; 
     } 
    }; 
    } 

但如果图像已在高度和宽度,它可能算作是可见的,即使图像没有加载

回答

1

你可以执行一些javascript来询问DOM。具体来说,属性HTMLImageElement

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

返回一个布尔如果浏览器已完成取 的图像,无论成功与否是真的。它也显示,如果图像 没有src值。