Images
UI Behavior (Real Project Context)β
Images are non-interactive by default, but they often act as:
- Clickable links
- Buttons (icons)
- Status indicators
- CAPTCHA or verification visuals
In automation, images are validated for presence, visibility, source, and click behavior β not visual correctness.
Typical HTML Patternsβ
Simple Imageβ
<img src="/assets/logo.png" alt="Company Logo">
Clickable Image (Link)β
<a href="/home">
<img src="home.png" alt="Home">
</a>
Image Used as Buttonβ
<img src="submit.png" onclick="submitForm()">
Locating Images (Stable Approaches)β
Preferred attributes:
altsrc(partial match)- Parent anchor (
<a>) if clickable
WebElement logo = driver.findElement(By.xpath("//img[@alt='Company Logo']"));
Validations You SHOULD Doβ
1. Image Is Displayedβ
Assert.assertTrue(logo.isDisplayed());
2. Image Source Is Correctβ
String src = logo.getAttribute("src");
Assert.assertTrue(src.contains("logo.png"));
3. Broken Image Validation (Important)β
Boolean isLoaded = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return arguments[0].complete && arguments[0].naturalWidth > 0", logo);
Assert.assertTrue(isLoaded);
Clicking on Imagesβ
If Image Is Inside a Linkβ
logo.click();
If Click Is Handled by JavaScriptβ
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", logo);
Image as Status Indicator (Real Scenario)β
Example: Green tick / red cross icons
WebElement statusIcon = driver.findElement(By.cssSelector("img.status"));
String src = statusIcon.getAttribute("src");
Assert.assertTrue(src.contains("success"));
Accessibility Validation (Bonus but Valuable)β
String altText = logo.getAttribute("alt");
Assert.assertFalse(altText.isEmpty());
Common Mistakes ββ
- Validating pixel colors (not Seleniumβs job)
- Using index-based XPath for images
- Ignoring broken image checks
- Clicking images without verifying click behavior
- Skipping accessibility (
alt) checks
Best Practices β β
- Validate image load using JS
- Prefer
alt-based locators - Validate purpose (link / button / indicator)
- Avoid visual comparisons
- Include accessibility checks where required
Interview Notes π―β
Q: Can Selenium validate images?
A: Yes β presence, visibility, source, and load status.
Q: How do you check a broken image?
A: Using JavaScript to verify naturalWidth.
Q: Can Selenium compare images visually?
A: No. Selenium is not a visual testing tool.
Real-Project Tip π‘β
Image validation is often part of smoke and accessibility tests, especially for branding-critical pages.
Summaryβ
- Images are validated functionally, not visually
- JS helps detect broken images
- Click behavior must be verified explicitly
- Accessibility matters