As technology has become embedded in today’s world, digital security has been a major concern and for good reason. Hackers use bots to operate web applications and access data such as user email addresses that lead to spamming, posing threats to privacy.
A measure to prevent such bot activity is to use Captcha (Completely Automated Public Turing test to tell Computers and Humans Apart). It is quite commonly used, which is why testers often search for means to test Captcha via Selenium.
For testers seeking tips on testing “Selenium Captcha”, “Selenium ReCaptcha” and wondering “how to handle captcha in selenium”, this article will help. It will discuss how Captcha can be tested via Selenium by QA engineers.
Read More: What is Browser Automation?
What is Captcha?
Through Captcha, the user is asked to perform a certain task, such as enter the text written in the image or click on the images from a set of different images that match the required criteria.
These tasks are meant to ascertain whether the user is a human or a bot. Since the task is dynamic, it can only successfully be carried out with human cognizance and correct interpretation of information – areas where the artificial intelligence of bots tends to fail.
Some variants of Captcha also support visually impaired individuals by generating audio instead of images.
Google’s open-source CAPTCHA widget, reCAPTCHA is widely used, since it supports major screen readers such as JAWS and NVDA for IE, Edge, or Chrome on Windows OS, ChromeVox for Chrome OS, and VoiceOver for Safari and Chrome on Mac OS.
Potential Test Cases around Captcha
Here are some potential test cases around captcha:
Functional Test Cases:
- Verify CAPTCHA appears on the intended forms/pages like login, sign-up, password reset, and contact forms.
- Verify CAPTCHA is required before form submission.
- Verify correct CAPTCHA entry allows form submission
Integration Test Cases:
- Verify third-party CAPTCHA services (like Google reCAPTCHA) are correctly integrated.
- Verify that site and CAPTCHA integration handle API/network errors properly.
Usability Test Cases
- Verify CAPTCHA is responsive and displays correctly on all screen sizes.
- Verify CAPTCHA is accessible
- Verify the image/audio CAPTCHA is clear and legible.
Performance Test Cases
- Verify that the system handles the load if the CAPTCHA service goes down.
- Verify CAPTCHA doesn’t significantly slow down page load times.
Handling Captcha Enabled Web Applications in Selenium
For web applications with Captcha enabled, automated UI testing could be an issue, especially as the step involving Captcha can create a hindrance in a test scenario. Moreover, the idea of Captcha itself does not align with automation, as doing so will defeat the purpose of prohibiting bots from performing activities on the application.
Thus, it is essential to efficiently handle Captcha in Selenium Testing to ensure that tests run seamlessly without any bottlenecks.
While automating Captcha is not the best practice, there are three efficient ways of handling Captcha in Selenium:
- By disabling the Captcha in the testing environment
- Adding a hook to click the Captcha checkbox
- By adding a delay to the Webdriver and manually solve Captcha while testing
How to Disable Captcha in the Test Environment
Disabling Captcha in the test environment would ensure that while testing a web application, the Captcha task is not required. While using Google’s open-source Captcha widget – reCAPTCHA v2, put in the Site Key and the Secret Key, (known as the test keys). As a result, all verification requests will pass, and automated UI testing can be conducted seamlessly.
- Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
- Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
However, while doing so, the reCAPTCHA widget will show a warning alert that ensures that the CAPTCHA is bypassed only for testing purposes and not in real-time access by users.
In the case of reCAPTCHA v3, the user needs to create a separate key for testing environments. Unlike reCAPTCHA v2, which has a generic testing key to support, reCAPTCHA v3 requires creating separate keys for the testing environment. Users can create keys for reCAPTCHA v3.
It is recommended to create one site key per web or mobile application. However, one can create separate site keys for staging and production environments. This is because there is a risk of contaminating reCAPTCHA risk analysis with the data from the test environment, which might alter the results of the analysis.
Also Read: How to handle Cookies in Selenium WebDriver
How to click the checkbox in reCaptcha during Selenium testing
By adding a hook to the code, users can bypass the Captcha while performing Automation Testing. The Captcha recognizes a bot clicking the checkbox element by the fact that it takes less time for the bot to click as compared to humans. Therefore, testers need to induce WebDriverWait, so that the element is clicked only when it becomes clickable. This bypasses the Captcha.
Here’s the code to add a hook that clicks on reCAPTCHA using Selenium and Java-
public class ReCaptcha_click { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe"); ChromeOptions options = new ChromeOptions(); options.addArguments("start-maximized"); options.addArguments("disable-infobars"); options.addArguments("--disable-extensions"); WebDriver driver = new ChromeDriver(options); driver.get("https://rsps100.com/vote/760"); new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@name, 'a-') and starts-with(@src, 'https://www.google.com/recaptcha')]"))); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.recaptcha-checkbox-checkmark"))).click(); } }
How to add delay and manually solve Captcha during Automation Testing
Firstly, this method is not completely automated and requires human intervention to solve the Captcha. Call it a semi-automated test.
In this method, a delay of 10-20s is introduced to freeze the captcha screen, so that the page does not suffer from the race condition, which generally happens while using automation testing on a web page with a Captcha element.
This is because automation testing is much faster than the focus on reCAPTCHA. Thereby, the password is entered much before the reCAPTCHA element even gets ready, leading to flaky tests.
By adding a delay to the testing, it ensures that by the time reCAPTCHA is ready, the form fill-up action waits and the racing condition can be evaded tactfully, streamlining the test and making it more accurate.
To delay execution of Selenium Webdriver for 10 seconds using Python, use the following command
import time time.sleep(10)
Here’s how delay can be added using Puppeteer for headless browsers:
const puppeteer = require('puppeteer'); const chromeOptions = { headless:false, defaultViewport: null}; (async function main() { const browser = await puppeteer.launch(chromeOptions); const page = await browser.newPage(); await page.goto('https://old.reddit.com/login'); })() await page.type('#user_reg', 'some_username'); await page.type('#passwd_reg', 'SuperStrongP@ssw0rd'); await page.type('#passwd2_reg', 'SuperStrongP@ssw0rd'); await page.click('#register-form button[type=submit]'); const chromeOptions = { headless:false, defaultViewport: null, slowMo:15, };
Captcha, which has been an important UI element to restrict bots from accessing a web application, has posed a major challenge for the testers performing UI testing using Selenium.
Since automating Captcha would defeat the purpose of having Captcha in the first place to ensure human interaction with the UI, it is very tricky to handle Captcha in Selenium.
However, with the test keys and hook, it is possible to ensure that the Captcha does not hamper UI testing. Captcha handling in Selenium is a mandatory skill of QAs because of how frequently Captcha is used as a security measure.
How to Bypass CAPTCHA With SeleniumBase and Undetected ChromeDriver for Testing
Bypassing CAPTCHAs in automated testing can be challenging since they are designed to prevent bots like Selenium from interacting automatically.
However, there are some ways to handle CAPTCHAs using tools like SeleniumBase and Undetected ChromeDriver for testing purposes. Here’s how:
Step 1. Install Dependencies
Install Python and then:
pip install seleniumbase undetected-chromedriver
Step 2. Use Undetected ChromeDriver with SeleniumBase
Customize SeleniumBase to use Undetected ChromeDriver as the browser driver.
import undetected_chromedriver.v2 as uc from seleniumbase import BaseCase class MyTest(BaseCase): def setUp(self): # Initialize undetected chromedriver manually self.driver = uc.Chrome() # Inject driver to SeleniumBase's BaseCase self._setup_driver(self.driver) def test_bypass_captcha(self): self.open("https://your-testing-site.com") # Your test steps here # Example: Fill login form, click buttons, etc. # If CAPTCHA appears, you may: # - Wait for manual input # - Use a CAPTCHA-solving service API # - Bypass CAPTCHA in the test environment by disabling it # Example: Wait for user to solve CAPTCHA manually self.wait_for_element("input#captcha-response", timeout=60)
Step 3. Handling CAPTCHA
- Manual intervention: Pause the test and let a tester solve CAPTCHA during automated test execution.
- CAPTCHA-solving services: Use APIs like 2Captcha, etc., where your script sends CAPTCHA images to the service and retrieves the answer. This would require integration.
- Disable CAPTCHA in test environment: If you control the environment, disable CAPTCHA during automated tests.
Read More: Test Case Vs Test Script
How to Handle Captcha with Selenium Stealth
Selenium Stealth is a Python package that modifies the browser’s JavaScript environment and behavior to mask Selenium automation fingerprints that websites often detect and trigger CAPTCHAs.
Here’s how you can handle CAPTCHA with Selenium Stealth
Step 1: Install Selenium and Selenium Stealth
pip install selenium selenium-stealth
Step 2: Basic Usage Example
from selenium import webdriver from selenium_stealth import stealth options = webdriver.ChromeOptions() # You can add options here, like headless mode, user agent, etc. driver = webdriver.Chrome(options=options) stealth(driver, languages=["en-US", "en"], vendor="Google Inc.", platform="Win32", webgl_vendor="Intel Inc.", renderer="Intel Iris OpenGL Engine", fix_hairline=True, ) driver.get("https://example.com") # Your test actions here driver.quit()
This minimizes the risk of being flagged as a bot by hiding Selenium traces.
Why use BrowserStack Automate for Selenium Tests?
Here’s why you should use BrowserStack Automate to run Selenium Tests:
- Parallel Testing: BrowserStack Automate lets you test on multiple device and browser combinations at once, speeding up test execution and providing quick feedback.
- Real Devices and Browsers: Testing on real devices and browsers ensures accurate performance insights, unlike emulators. You can test on the latest devices without buying them.
- Dedicated Dashboard: Automate offers a dashboard to track and manage your tests, showing test statuses (Pass/Fail/Pending), device details, test duration, screenshots, and more.
- Custom Reports with Artifacts: Generate detailed, customized reports including test status, device/browser configurations, video recordings, and screenshots.
- Easy Integration with CI/CD: Seamlessly integrate with CI/CD tools like Jenkins, TeamCity, and TravisCI for faster, reliable, and consistent application delivery.
Conclusion
Ideally, it is recommended as a best practice to separate the test cases involving Captcha and run them separately. Additionally, if the tests are not conducted on the live code that is deployed already, then the testers could disable the Captcha module when they perform automated UI testing.
Bear in mind that Selenium tests must be run on real devices for accurate results. Start running tests on 3500+ real browsers and devices on BrowserStack’s real device cloud. Run parallel tests on a Cloud Selenium Grid to get faster results without compromising on accuracy. Testers can also conduct Cypress testing on 30+ real browser versions across Windows and macOS. Detect bugs before users do by testing software in real user conditions with BrowserStack Automate.
Useful Resources for Automation Testing in Selenium
Methods, Classes, and Commands
- Selenium Commands every Developer or Tester must know
- Selenium WebElement Commands
- Desired Capabilities in Selenium Webdriver
- Assert and Verify Methods in Selenium
- Understanding System setProperty in Selenium
- Select Class in Selenium : How to select a value in dropdown list?
- SendKeys in Selenium WebDriver
- getAttribute() method in Selenium: What, Why, and How to use
- How does Selenium isDisplayed() method work?
- findElement vs findElements in Selenium
- Types of Listeners in Selenium (with Code Examples)
- How to set Proxy in Firefox using Selenium WebDriver?
Configuration
- How to set up Selenium on Visual Studio
- How to configure Selenium in Eclipse
- Maven Dependency Management with Selenium
- How to Build and Execute Selenium Projects
XPath
- How to use XPath in Selenium?
- How to find element by XPath in Selenium with Example
- Top Chrome Extensions to find Xpath in Selenium
Locators and Selectors
- Locators in Selenium: A Detailed Guide
- CSS Selector in Selenium: Locate Elements with Examples
- How to Create Object Repository in Selenium
Waits in Selenium
- Wait Commands in Selenium C and C#
- Selenium Wait Commands: Implicit, Explicit, and Fluent Wait
- Understanding Selenium Timeouts
- Understanding ExpectedConditions in Selenium
- Understanding Role of Thread.sleep() in Selenium
Frameworks in Selenium
- Data Driven Framework in Selenium
- Implementing a Keyword Driven Framework for Selenium: A Practical Guide
- Hybrid Framework in Selenium
Miscellaneous
- How to create Selenium test cases
- How to set Proxy in Selenium?
- Difference between Selenium Standalone server and Selenium server
- Exception Handling in Selenium WebDriver
- How to use JavascriptExecutor in Selenium
- How to run your first Selenium test script
- Parallel Testing with Selenium
Best Practices, Tips and Tricks
- Top 5 Challenges Faced During Automation Selenium Testing
- 5 Selenium tricks to make your life easier
- 6 Things to avoid when writing Selenium Test Scripts
- Best Practices for Selenium Test Automation
- Why you should pay attention to flaky Selenium tests
- How to start with Selenium Debugging
- How to make your Selenium test cases run faster
- How to upgrade from Selenium 3 to Selenium 4
- Why you should move your testing to a Selenium Cloud?
Design Patterns in Selenium: Page Object Model and Page Factory
- Design Patterns in Selenium
- Page Object Model and Page Factory in Selenium
- Page Object Model and Page Factory in Selenium C#
- Page Object Model in Selenium and JavaScript
- Page Object Model and Page Factory in Selenium Python
Action Class
- How to handle Action class in Selenium
- How to perform Mouse Hover Action in Selenium
- Understanding Click Command in Selenium
- How to perform Double Click in Selenium?
- How to Drag and Drop in Selenium?
- How to Scroll Down or Up using Selenium Webdriver
- How To verify Tooltip Using Selenium
TestNG and Selenium
- Database Testing using Selenium and TestNG
- How to use DataProvider in Selenium and TestNG?
- All about TestNG Listeners in Selenium
- How to run parallel test cases in TestNG
- How to use TestNG Reporter Log in Selenium: Tutorial
- Prioritizing tests in TestNG with Selenium
JUnit and Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- How to run JUnit Parameterized Test in Selenium
- How to write JUnit test cases
- JUnit Testing Tutorial: JUnit in Java
- How to create JUnit Test Suite? (with Examples)
Use Cases
- Handling Login Popups in Selenium WebDriver and Java
- How to Launch Browser in Selenium
- How to handle Alerts and Popups in Selenium?
- How to get Selenium to wait for a page to load
- How to Find Element by Text in Selenium: Tutorial
- How to Read/Write Excel Data using Apache POI Selenium
- How to handle Captcha in Selenium
- How to handle multiple windows in Selenium?
- How to handle Multiple Tabs in Selenium
- How to find broken links in Selenium
- How to handle Cookies in Selenium WebDriver
- How to handle iFrame in Selenium
- How to handle Web Tables in Selenium
- How To Validate Text in PDF Files Using Selenium Automation
- Get Current URL in Selenium using Python: Tutorial
Types of Testing with Selenium
- Different Testing Levels supported by Selenium
- How to perform UI Testing with Selenium
- Regression Testing with Selenium: Tutorial
- UI Automation using Python and Selenium: Tutorial
- How to Run Visual Tests with Selenium: Tutorial
- How to perform ETL Automation using Selenium
- Cross Browser Testing in Selenium : Tutorial