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
Comments
Post a Comment