我看到有一个问题: Selenium-Webdriver Ruby->单击后如何等待图像完全加载
但是似乎没有人直接回答:我需要等待使用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]plete", 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
发布评论