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 contains valid image data). Is such thing possible?
Use the <img> tag to collect details of the images present on the page. For each <img> tag, get the attribute <src> from the tag. Convert the path obtained from the <src> attribute to an 'Absolute Path. ' Conversion to absolute path might not be required for Selenium Java, Selenium C#, and Selenium Python.
We can verify whether an element is present or visible in a page with Selenium webdriver. To check the presence of an element, we can use the method – findElements. The method findElements returns a list of matching elements. Then, we have to use the method size to get the number of items in the list.
We can also confirm if an element is visible with the help of isDisplayed() method. This method returns a true or a false value. In case the element is invisible, the method returns a false value.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With