0
0
Selenium Pythontesting~15 mins

Screenshot on failure in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Capture screenshot when login fails
Preconditions (2)
Step 1: Enter 'wronguser@example.com' in the email input field with id 'email'
Step 2: Enter 'wrongpassword' in the password input field with id 'password'
Step 3: Click the login button with id 'loginBtn'
Step 4: Wait for the error message with id 'errorMsg' to appear
✅ Expected Result: Login fails, error message is displayed, and a screenshot of the page is saved
Automation Requirements - selenium
Assertions Needed:
Verify that the error message element with id 'errorMsg' is visible
Verify that a screenshot file is saved when the test fails
Best Practices:
Use explicit waits to wait for elements
Use try-except blocks to catch failures and take screenshots
Use meaningful element locators like IDs
Save screenshots with timestamped filenames
Automated Solution
Selenium Python
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

class TestLoginScreenshotOnFailure(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()
        self.driver.get('https://example.com/login')
        self.wait = WebDriverWait(self.driver, 10)

    def test_invalid_login_screenshot_on_failure(self):
        driver = self.driver
        try:
            email_input = self.wait.until(EC.presence_of_element_located((By.ID, 'email')))
            email_input.clear()
            email_input.send_keys('wronguser@example.com')

            password_input = driver.find_element(By.ID, 'password')
            password_input.clear()
            password_input.send_keys('wrongpassword')

            login_button = driver.find_element(By.ID, 'loginBtn')
            login_button.click()

            # Wait for error message
            error_msg = self.wait.until(EC.visibility_of_element_located((By.ID, 'errorMsg')))

            # Assert error message is displayed
            self.assertTrue(error_msg.is_displayed(), 'Error message should be visible')

        except (AssertionError, TimeoutException) as e:
            timestamp = time.strftime('%Y%m%d-%H%M%S')
            screenshot_name = f'screenshot_failure_{timestamp}.png'
            driver.save_screenshot(screenshot_name)
            raise e

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

if __name__ == '__main__':
    unittest.main()

This test uses unittest and Selenium WebDriver for Python.

setUp: Opens the browser and navigates to the login page.

test_invalid_login_screenshot_on_failure: Enters invalid credentials, clicks login, and waits for the error message.

If the error message is not visible or any assertion fails, it catches the exception, takes a screenshot with a timestamped filename, and then re-raises the error to fail the test.

tearDown: Closes the browser after the test.

This approach ensures that if the test fails, you get a screenshot to help understand what went wrong.

Common Mistakes - 4 Pitfalls
Using time.sleep() instead of explicit waits
Not catching exceptions to take screenshots on failure
Using brittle locators like absolute XPath
Saving screenshots with fixed filenames
Bonus Challenge

Now add data-driven testing with 3 different invalid login inputs to verify screenshots on each failure

Show Hint