How to check if an image is displayed on page using Selenium?

SeleniumAutomation TestingTesting Tools

We can check if an image is displayed on page with Selenium. To verify an image we shall take the help of Javascript Executor. We shall utilize executeScript method to execute the Javascript commands in Selenium.

Then pass the command return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0 as a parameter to that method. Moreover, the statement import org.openqa.selenium.JavascriptExecutor has to be added in code.

Syntax

WebElement i = driver.findElement(By.xpath("//img[@title='Tutorialspoint']"));

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

Let us check if the below image is present on page −

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ImageChk{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      //identify image
      WebElement i = driver.findElement
      (By.xpath("//img[@title='Tutorialspoint']"));
      // Javascript executor to check image
      Boolean p = (Boolean) ((JavascriptExecutor)driver) .executeScript("return arguments[0].complete " + "&& typeof arguments[0].naturalWidth != \"undefined\" " + "&& arguments[0].naturalWidth > 0", i);

      //verify if status is true
      if (p) {
         System.out.println("Logo present");
      } else {
         System.out.println("Logo not present");
      }
      driver.quit();
   }
}

Output

raja
Published on 28-Dec-2020 16:10:45
Advertisements