Handling CAPTCHAs (strategies) in Selenium Python - Build an Automation Script
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 class LoginPage: def __init__(self, driver): self.driver = driver self.email_input = (By.ID, 'email') self.password_input = (By.ID, 'password') self.captcha_frame = (By.CSS_SELECTOR, 'iframe[src*="captcha"]') self.login_button = (By.ID, 'login-btn') def enter_email(self, email): WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.email_input)).send_keys(email) def enter_password(self, password): WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(self.password_input)).send_keys(password) def is_captcha_present(self): try: WebDriverWait(self.driver, 5).until(EC.frame_to_be_available_and_switch_to_it(self.captcha_frame)) self.driver.switch_to.default_content() return True except: return False def click_login(self): WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable(self.login_button)).click() def test_login_with_captcha(): driver = webdriver.Chrome() driver.get('https://example.com/login') login_page = LoginPage(driver) login_page.enter_email('testuser@example.com') login_page.enter_password('TestPass123!') if login_page.is_captcha_present(): print('CAPTCHA detected. Manual intervention required or test skipped.') driver.quit() return login_page.click_login() # Verify dashboard URL WebDriverWait(driver, 10).until(EC.url_contains('/dashboard')) assert '/dashboard' in driver.current_url, 'Dashboard URL not loaded after login' # Verify welcome message presence welcome_msg = WebDriverWait(driver, 10).until( EC.visibility_of_element_located((By.ID, 'welcome-msg')) ) assert welcome_msg.is_displayed(), 'Welcome message not displayed on dashboard' driver.quit() if __name__ == '__main__': test_login_with_captcha()
This script uses Selenium with Python to automate login on a page that may have a CAPTCHA.
The LoginPage class encapsulates page elements and actions, following the Page Object Model for clarity and reuse.
We check if a CAPTCHA iframe is present by waiting for it briefly. If found, the test prints a message and stops, because automated CAPTCHA solving is not done here.
If no CAPTCHA is detected, the script enters credentials, clicks login, and waits for the dashboard URL and welcome message to confirm successful login.
Explicit waits ensure the script waits for elements properly, avoiding timing issues.
This approach respects best practices by not trying to bypass CAPTCHA automatically, which is often not possible or ethical, and instead detects it to handle accordingly.
Now add data-driven testing with 3 different sets of login credentials, including one invalid user.
Practice
Solution
Step 1: Understand CAPTCHA purpose
CAPTCHAs are security tools to stop bots and automated scripts from accessing certain parts of websites.Step 2: Selenium's limitation
Selenium automates browsers but cannot solve CAPTCHAs because they require human-like recognition or external solving.Final Answer:
CAPTCHAs are designed to block automated scripts from interacting with the page. -> Option AQuick Check:
CAPTCHA blocks automation = D [OK]
- Thinking Selenium can solve CAPTCHAs automatically
- Believing CAPTCHAs need special plugins
- Assuming Selenium can't open pages with CAPTCHAs
Solution
Step 1: Identify correct pause method in Python
Python's standard way to pause execution is using time.sleep(seconds), so time.sleep(30) pauses for 30 seconds.Step 2: Check Selenium driver methods
Selenium WebDriver does not have pause() or wait() methods directly; wait() is for conditions, not fixed sleep.Final Answer:
time.sleep(30) -> Option AQuick Check:
Pause test with time.sleep() = C [OK]
- Using driver.pause() which doesn't exist
- Calling sleep() without importing time
- Confusing wait() with sleep()
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://example.com/captcha')
time.sleep(60) # wait for manual CAPTCHA solve
button = driver.find_element(By.ID, 'submit')
button.click()What will happen if the CAPTCHA is not solved within 60 seconds?
Solution
Step 1: Analyze the code flow
The script waits 60 seconds for manual CAPTCHA solving, then tries to click the submit button.Step 2: Understand CAPTCHA effect
If CAPTCHA is not solved, the submit button is usually disabled or blocked, so clicking won't succeed or may cause failure.Final Answer:
The test will fail because the CAPTCHA blocks the submit button. -> Option BQuick Check:
Unsolved CAPTCHA blocks submit = B [OK]
- Assuming Selenium solves CAPTCHA automatically
- Thinking submit button always clickable
- Expecting syntax errors from this code
from selenium.webdriver.common.by import By
driver.get('https://example.com')
driver.find_element(By.ID, 'captcha').click()But it throws NoSuchElementException. What is the likely cause?
Solution
Step 1: Understand NoSuchElementException cause
This error means Selenium cannot find the element with id 'captcha' on the page.Step 2: Check test environment setup
If CAPTCHA is disabled in test environment, the element won't exist, causing this error.Final Answer:
The CAPTCHA element is not present because it is disabled in the test environment. -> Option CQuick Check:
Disabled CAPTCHA means no element = A [OK]
- Thinking 'id' locator syntax is wrong
- Assuming driver.get() fails silently
- Believing click() is unsupported
Solution
Step 1: Evaluate automation vs reliability
CAPTCHA solving services may be unreliable or costly; manual solving slows tests; ignoring CAPTCHA causes failures.Step 2: Consider test environment control
Disabling CAPTCHA in test environment allows smooth automated tests without blocking, improving reliability and speed.Final Answer:
Disable CAPTCHA only in the test environment and run tests without CAPTCHA. -> Option DQuick Check:
Disable CAPTCHA in test env = best balance = A [OK]
- Relying on unreliable CAPTCHA solving services
- Ignoring CAPTCHA causing test failures
- Pausing tests slows automation
Ready to prove it?
Pass the test and this pattern moves unknown
