How to Take Screenshots in Selenium Automatically on Failure

 ๐Ÿ“ธ Automatically Take Screenshots on Test Failure with Selenium

✅ Why Take Screenshots?

Screenshots help you:


Visually debug test failures.


Capture the exact state of the application during a failure.


Improve test reporting.


๐Ÿงช Using unittest + Selenium

Here’s how to capture screenshots automatically when a test fails.


๐Ÿ”ง 1. Basic Setup

Install Selenium (if you haven’t already):


bash

Copy

Edit

pip install selenium

๐Ÿ“‚ 2. Sample Code with Screenshot Logic

python

Copy

Edit

import unittest

from selenium import webdriver

from selenium.webdriver.common.by import By

import os

import time


class MyTestCase(unittest.TestCase):


    def setUp(self):

        self.driver = webdriver.Chrome()

        self.driver.get("https://example.com")  # Replace with your URL


    def tearDown(self):

        # If the test failed, take a screenshot

        for method, error in self._outcome.errors:

            if error:

                test_method_name = self._testMethodName

                timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")

                filename = f"screenshots/{test_method_name}_{timestamp}.png"

                os.makedirs(os.path.dirname(filename), exist_ok=True)

                self.driver.save_screenshot(filename)

                print(f"๐Ÿ“ธ Screenshot saved: {filename}")

        self.driver.quit()


    def test_example(self):

        # This will fail for demo purposes

        self.assertTrue(False, "Forcing a failure to test screenshot")


if __name__ == "__main__":

    unittest.main()

๐Ÿ“ What Happens

If the test fails, the tearDown() method checks for errors.


If an error is found, it takes a screenshot using driver.save_screenshot().


The image is saved with a timestamp in a /screenshots directory.


๐Ÿ”„ Tips for Better Use

Use setUpClass and tearDownClass for shared driver setup across tests.


You can integrate this logic into a base test class for reuse.


For large projects, integrate with test reporting tools (like Allure or HTMLTestRunner).


๐Ÿ Conclusion

Taking screenshots on test failure in Selenium using Python’s unittest is simple and extremely useful. Just add the screenshot logic in your tearDown() method, and you’ll capture failures visually—automatically.

Learn Selenium JAVA Training in Hyderabad

Read More

Cross-Browser Testing with Selenium WebDriver

Implicit vs Explicit Waits in Selenium – What’s the Difference?

Data-Driven Testing Using Excel Files in Selenium + Java

How to Handle Web Tables in Selenium WebDriver

Visit Our Quality Thought Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Installing Tosca: Step-by-Step Guide for Beginners

Why Data Science Course?