Last modified: Nov 22, 2024 By Alexander Williams

Python Selenium: How to Validate Images - Complete Tutorial

Image validation is crucial in web automation testing to ensure proper content rendering. In this guide, we'll explore various methods to validate images using selenium with Python.

1. Checking Image Presence

The first step in image validation is verifying if an image element exists on the page. We can use Selenium's element locators to find images.


from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://example.com")

# Find image by various locators
image = driver.find_element(By.TAG_NAME, "img")
images = driver.find_elements(By.CSS_SELECTOR, "img.product-image")

2. Validating Image Properties

Once you locate an image, you can validate its attributes like source URL, dimensions, and alt text. This is essential for ensuring proper image implementation.


def validate_image_properties(image_element):
    # Check image attributes
    src = image_element.get_attribute("src")
    alt = image_element.get_attribute("alt")
    width = image_element.get_attribute("width")
    height = image_element.get_attribute("height")
    
    # Validate attributes
    assert src is not None, "Image source is missing"
    assert alt is not None, "Alt text is missing"
    print(f"Image validated: {src}")

3. Checking Image Loading Status

To ensure images are loading correctly, we can use JavaScript operations with execute_script to check the complete loading status.


def is_image_loaded(driver, image_element):
    # Execute JavaScript to check image loading
    return driver.execute_script("""
        return arguments[0].complete && 
        typeof arguments[0].naturalWidth != "undefined" && 
        arguments[0].naturalWidth > 0
    """, image_element)

4. Implementing a Complete Image Validation

Here's a comprehensive example that combines all validation methods. This approach ensures thorough image testing on your web pages.


def validate_all_images(driver):
    images = driver.find_elements(By.TAG_NAME, "img")
    broken_images = []
    
    for img in images:
        try:
            # Check if image is displayed
            if not img.is_displayed():
                continue
                
            # Validate properties
            validate_image_properties(img)
            
            # Check loading status
            if not is_image_loaded(driver, img):
                broken_images.append(img.get_attribute("src"))
                
        except Exception as e:
            print(f"Error validating image: {str(e)}")
            
    return broken_images

5. Handling Broken Images

To identify broken images, we can check the natural width and height properties. Images that fail to load typically have these values set to 0.


def check_broken_images(driver):
    script = """
    return arguments[0].naturalWidth === 0 
           || arguments[0].naturalHeight === 0;
    """
    images = driver.find_elements(By.TAG_NAME, "img")
    
    for img in images:
        is_broken = driver.execute_script(script, img)
        if is_broken:
            print(f"Broken image found: {img.get_attribute('src')}")

Conclusion

Image validation is a critical aspect of web testing. By using these Selenium techniques, you can ensure your web applications display images correctly and provide a good user experience.

For more advanced testing scenarios, consider integrating these methods with Pytest for structured testing and proper logging implementation.