Nic*_*tti 5 java selenium webdriver selenium-webdriver
看到有一个问题:Selenium-Webdriver Ruby --> How to wait for images to be full load after click
但似乎没有人直接回答:我需要等待图像完全加载,而不仅仅是在 DOM 中呈现,使用 selenium WebDriver。我该怎么办? 目前我正在使用
public static void waitUntilVisible(WebDriver webDriver, By locator) {
WebDriverWait driverWait = new WebDriverWait(webDriver, TIMEOUT);
driverWait.until(visibilityOfElementLocated(locator));
}
Run Code Online (Sandbox Code Playgroud)
它使用
/**
* 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;
}
};
}
Run Code Online (Sandbox Code Playgroud)
但如果图像已经有高度和宽度,即使图像尚未加载,它也可能被视为可见
您可以执行一些 javascript 来询问 DOM。具体来说,就是HTMLImageElement的complete属性。
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);
}
}
);
}
Run Code Online (Sandbox Code Playgroud)
但请注意complete:
返回一个布尔值,如果浏览器已完成获取图像,无论成功与否。如果图像没有 src 值,它也会显示为真。
| 归档时间: |
|
| 查看次数: |
6368 次 |
| 最近记录: |