0
0
Selenium Pythontesting~5 mins

Screenshot on failure in Selenium Python

Choose your learning style9 modes available
Introduction

Taking a screenshot when a test fails helps you see what went wrong. It shows the exact page state at the failure moment.

When a test case does not pass and you want to check the page visually.
When debugging UI issues that are hard to find by logs alone.
When running tests on remote or headless browsers and you cannot see the screen.
When you want to keep evidence of failures for reports or sharing with teammates.
Syntax
Selenium Python
try:
    # test steps
    assert condition
except Exception as e:
    driver.save_screenshot('failure.png')
    raise e

Use driver.save_screenshot('filename.png') to save the current browser view.

Place screenshot code inside an exception block to capture failures only.

Examples
This saves a screenshot if the page title is not as expected.
Selenium Python
try:
    assert driver.title == 'Expected Title'
except AssertionError:
    driver.save_screenshot('title_fail.png')
    raise
This captures a screenshot if clicking the button fails.
Selenium Python
try:
    element = driver.find_element(By.ID, 'submit')
    element.click()
except Exception:
    driver.save_screenshot('click_fail.png')
    raise
Sample Program

This test opens Google, searches for 'OpenAI', and checks the page title. If any step fails, it saves a screenshot named 'failure_screenshot.png' and prints a message.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

def test_google_search():
    driver = webdriver.Chrome()
    try:
        driver.get('https://www.google.com')
        time.sleep(1)  # wait for page load
        assert 'Google' in driver.title
        search_box = driver.find_element(By.NAME, 'q')
        search_box.send_keys('OpenAI')
        search_box.submit()
        time.sleep(2)  # wait for results
        assert 'OpenAI' in driver.title
    except Exception as e:
        driver.save_screenshot('failure_screenshot.png')
        print('Test failed, screenshot saved.')
        raise
    finally:
        driver.quit()

if __name__ == '__main__':
    test_google_search()
OutputSuccess
Important Notes

Use meaningful screenshot file names with timestamps to avoid overwriting.

Make sure the folder where screenshots are saved exists or handle path creation.

Use explicit waits instead of sleep for more reliable tests.

Summary

Taking screenshots on failure helps find UI problems quickly.

Use try-except blocks to catch failures and save screenshots.

Review screenshots to understand what the user saw at failure time.