Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 contains valid image data). Is such thing possible?

like image 935
Matěj Zábský Avatar asked Oct 29 '10 13:10

Matěj Zábský


People also ask

How can you find all the image present in your web page in Selenium?

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.

How can you find if an element is displayed on the screen in Selenium?

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.

How do you check if an element is displayed or not?

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.


2 Answers

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.

like image 41
thejh Avatar answered Oct 03 '22 08:10

thejh


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.

like image 172
Hari Reddy Avatar answered Oct 03 '22 08:10

Hari Reddy