Handling Images
Verifying images and logos in Selenium automation can mean a few different things, depending on your test requirement. Here are the most common scenarios and how you can automate each one in Selenium:
1. Verify Image or Logo is Displayed
Check if the image element is present and visible on the page.
WebElement logo = driver.findElement(By.id("companyLogo"));
if (logo.isDisplayed()) {
System.out.println("Logo is displayed!");
} else {
System.out.println("Logo is NOT displayed!");
}
2. Verify the Image Source (src Attribute)
Check that the image source URL is correct (for branding or dynamic images)
String logoSrc = logo.getAttribute("src");
if (logoSrc.equals("https://yourwebsite.com/images/logo.png")) {
System.out.println("Logo src is correct!");
} else {
System.out.println("Logo src is NOT correct!");
}
3. Verify Image Loads Properly (Not Broken)
Check if the image actually loads (not just present in HTML), by validating the naturalWidth property using JavaScript.
Boolean imageLoaded = (Boolean) ((JavascriptExecutor)driver).executeScript(
"return arguments[0].complete && " +
"typeof arguments[0].naturalWidth != 'undefined' && " +
"arguments[0].naturalWidth > 0", logo);
if (imageLoaded) {
System.out.println("Logo is loaded successfully!");
} else {
System.out.println("Logo is broken or not loaded!");
}
4. Verify Image Alt Attribute (Accessibility Testing)
Ensure alt text is present and correct for accessibility.
String altText = logo.getAttribute("alt");
if (altText.equals("Your Company Logo")) {
System.out.println("Alt text is correct!");
} else {
System.out.println("Alt text is missing or incorrect!");
}
5. (Advanced) Verify Image Pixels/Visual Match
If you need to verify that the image looks exactly as expected (pixel match), Selenium alone is not enough.
You need to:
- Take a screenshot of the image or logo.
- Compare it with a baseline/reference image using tools like Ashot, Sikuli, or integrate with image comparison libraries.
Example using Ashot library:
// Not pure Selenium: add Ashot dependency to project first
Screenshot imageScreenshot = new AShot().takeScreenshot(driver, logo);
// Compare imageScreenshot.getImage() with your baseline image
Summary Table
Verification Type | How to Check |
Image is displayed | isDisplayed() |
Image source is correct | getAttribute(“src”) |
Image loads (not broken) | JavaScript: check naturalWidth > 0 |
Image alt attribute | getAttribute(“alt”) |
Visual (pixel) match | Use Ashot, Sikuli, or external comparison tools |