0
0
Selenium Pythontesting~10 mins

Screenshot on failure in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage, tries to find a button, clicks it, and verifies the page title. If the test fails, it takes a screenshot to help diagnose the problem.

Test Code - unittest
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import unittest

class TestScreenshotOnFailure(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)

    def test_click_button_and_check_title(self):
        driver = self.driver
        driver.get('https://example.com')
        try:
            button = driver.find_element(By.ID, 'submit-btn')
            button.click()
            self.assertEqual(driver.title, 'Expected Title')
        except Exception as e:
            driver.save_screenshot('failure_screenshot.png')
            raise e

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and WebDriver Chrome browser opensChrome browser window is open and ready-PASS
2Browser navigates to 'https://example.com'Page 'https://example.com' is loaded in browser-PASS
3Find element with ID 'submit-btn'Button with ID 'submit-btn' is present on the page-PASS
4Click the 'submit-btn' buttonButton is clicked, page may change-PASS
5Check if page title equals 'Expected Title'Page title is checkedAssert page title == 'Expected Title'PASS
6Test ends and browser closesBrowser window is closed-PASS
Failure Scenario
Failing Condition: Element with ID 'submit-btn' is not found or page title is not 'Expected Title'
Execution Trace Quiz - 3 Questions
Test your understanding
What happens if the button with ID 'submit-btn' is not found?
AThe test passes without clicking the button
BThe test ignores the missing button and continues
CA screenshot is taken and the test fails with NoSuchElementException
DThe browser closes immediately without error
Key Result
Taking a screenshot immediately when a test fails helps quickly understand what the browser showed at failure time, making debugging easier.