等待图像完全加载Selenium WebDriver [英] Wait for an image to be fully loaded Selenium WebDriver
问题描述
我看到有一个问题:但是似乎没有人直接回答:我需要等待使用Selenium WebDriver将图像完全加载,而不仅仅是在DOM中显示.我该怎么办?目前我正在使用
But it seems that nobody has directly answered that: I need to wait for an image to be fully loaded, not just to present in the DOM, using selenium WebDriver. What should I do?Currently I'm using
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;
}
};
}
但是,如果图像已经具有高度和宽度,即使未加载图像,它也可能被视为可见
but if an image has already an height and width it's probably counted as visible even if the image hasn't loaded
推荐答案
您可以执行一些JavaScript来查询DOM.具体来说,是 HTMLImageElement 的complete
属性.. >
You could execute some javascript to interrogate the DOM. Specifically, the complete
property of an 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
:
如果浏览器已完成获取操作,则返回一个布尔值,该布尔值为true 图像,无论是否成功.如果图像还显示为真 没有src值.
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.
这篇关于等待图像完全加载Selenium WebDriver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!