0
0
Selenium Pythontesting~10 mins

Handling CAPTCHAs (strategies) in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test simulates a login attempt on a website with a CAPTCHA. It verifies that the CAPTCHA is detected and the test handles it by skipping the login to avoid failure.

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 TestLoginWithCaptcha(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/login')

    def test_login_handling_captcha(self):
        driver = self.driver
        try:
            captcha = driver.find_element(By.ID, 'captcha')
            print('CAPTCHA detected, skipping login.')
            self.skipTest('CAPTCHA present, manual intervention needed')
        except NoSuchElementException:
            username = driver.find_element(By.ID, 'username')
            password = driver.find_element(By.ID, 'password')
            username.send_keys('testuser')
            password.send_keys('password123')
            driver.find_element(By.ID, 'login-button').click()
            welcome = driver.find_element(By.ID, 'welcome-message')
            self.assertTrue(welcome.is_displayed())

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 4 Steps
StepActionSystem StateAssertionResult
1Test starts and opens Chrome browserBrowser opened at https://example.com/login showing login form-PASS
2Test tries to find CAPTCHA element by ID 'captcha'Page shows login form with CAPTCHA presentCheck if CAPTCHA element is foundPASS
3CAPTCHA detected, test skips login to avoid failureTest logs 'CAPTCHA detected, skipping login.' and skips testSkip test due to CAPTCHA presencePASS
4Browser closes after test endsBrowser closed-PASS
Failure Scenario
Failing Condition: CAPTCHA is not detected but login fails due to incorrect credentials or page changes
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test do when it finds a CAPTCHA on the login page?
AAttempts to solve the CAPTCHA automatically
BSkips the login test to avoid failure
CIgnores the CAPTCHA and proceeds with login
DFails the test immediately
Key Result
When testing pages with CAPTCHAs, detect their presence first and skip or handle tests accordingly to avoid false failures.