2017-03-07 61 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值。