Selenium - check if an image is displayed on page Selenium - check if an image is displayed on page selenium selenium

Selenium - check if an image is displayed on page


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.