开发者

Selenium - check if an image is displayed on page

I'm creating a suite of Selenium tests for an web album application. I would like to test whether an image is actually displayed (it c开发者_如何学JAVAontains valid image data). Is such thing possible?


I faced this similar situation before where the src of the image is as expected but the image is not displayed on the page.

You can check if the image is getting displayed or not by using the JavaScriptExcecutor.

Use the following code - Pass the WebElement (image) -

 Object result = ((JavascriptExecutor) driver).executeScript(
   "return arguments[0].complete && "+
   "typeof arguments[0].naturalWidth != \"undefined\" && "+
   "arguments[0].naturalWidth > 0", image);

    boolean loaded = false;
    if (result instanceof Boolean) {
      loaded = (Boolean) result;
      System.out.println(loaded);
    }

You can verify if the image has actually loaded on the webpage by doing this.


If you're using Java, selenium has a method named eval or so. You give it a javascript string and it gives you the result as a string. For example, you could try this (in one line):

var req = new XMLHttpRequest();
req.open('get', document.getElementById('imageid').src, false);
req.send(null);
req.status==200

This should return "true" for status 200 or "false" for something else.


If you are willing to use the TestPlan frontend to Selenium there a few options. Once you have the URL of the image you can grab this URL and inspect the returned headers. you can also save the data to a file if you'd like to manually inspect it. Or you can write a validator in Java to take that data and check to see if it actually decodes.

If you're willing to try it out then I'll write you a sample script. I can even do a quick image validator function if you'd like.


Use this one liner function:

Boolean isImageLoaded = (Boolean) ((JavascriptExecutor)driver).executeScript("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", imageWebElement);

where:

imageWebElement = WebElement to locate image on page

isImageLoaded = Result in boolean (return true if image is present, false if its not)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜