How To Handle Captcha In Selenium

Posted by Ria Dayal | January 6, 2022
Automation • Selenium Java •

104990 Views | 15 Min Read

With the rapidly evolving technology due to its ever-increasing demand in today’s world, Digital Security has become a major concern for the Software Industry. There are various ways through which Digital Security can be achieved, Captcha being one of them.Captcha is easy for humans to solve but hard for “bots” and other malicious software to figure out. However, Captcha has always been tricky for the testers to automate, as many of them don’t know how to handle captcha in Selenium or using any other test automation framework.

Handle Captcha In Selenium

Source

Now, let’s see what Captcha is and how to automate Captcha in Selenium WebDriver. We will also read in detail about ReCAPTCHA, which is hosted by Google and protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart.

Let’s deep dive into the world of Captcha and reCAPTCHA and see how to handle image Captcha in Selenium WebDriver.

What is Captcha?

CAPTCHA stands for Completely Automated Public Turing Test To Tell Computers And Humans Apart and is a type of challenge-response test used to ascertain whether the user is a human or a bot. The primary purpose of Captcha is to prevent bots or automated programs from using various types of computing services or collecting certain types of sensitive information such as email addresses, phone numbers, etc.

Captcha For Selenium

The image shown here is one generated by reCAPTCHA. Captchas are mostly dynamic and are intended to defeat automation frameworks like Selenium. However, since they are dynamic, they can be carried out successfully only with human interpretation and analysis, and as a result, most of the automated bots fail.

Different test cases possible around Captcha

Before we jump into handling Captcha scenarios in Selenium, let us first see the different test cases that are possible around Captcha. They are:

  1. To verify that the application accepts only valid Captcha.
  2. To verify that the Captcha code is case-sensitive.
  3. To verify that an error message is displayed if a user enters an incorrect Captcha code.
  4. To verify that the Captcha code on the screen is properly visible to the user or not.
  5. To verify that a new Captcha is getting generated on page refresh.
  6. To verify that a new Captcha is generated if a user enters an incorrect Captcha code.
  7. To verify that Copy & Paste action doesn’t work on the Captcha input box.
  8. To verify that the application is not accepting partial Captcha code.

Also read: 24 Testing Scenarios you should not automate with Selenium

Different ways to handle Captcha in Selenium

Although automating Captchas in Selenium is not the best practice, automation engineers have still been trying to find ways to automate Captcha in Selenium for a very long time to achieve complete automation of their web pages.

Also read: 16 Selenium Best Practices For Efficient Test Automation

However, Captcha forms vary a lot. For example, they can be visual or drag and drop, etc. Some Captchas even use audio to support visually challenged individuals. This diverse form of Captchas makes it challenging to automate.

Now that we have seen the possible test cases around Captchas, how do we efficiently handle Captcha in Selenium so that the tests run seamlessly without any hindrances? As of writing this article, the latest version of Selenium is Selenium 4. This Selenium WebDriver Tutorial for beginners and professionals will help you learn what’s new in Selenium 4 (Features and Improvements).

,

You can follow the LambdaTest YouTube Channel and stay updated with the latest tutorials around Selenium testing, Cypress testing, CI/CD, and more.

There are three ways by which we can efficiently handle Captcha in Selenium:

  • By disabling Captchas in test environments
  • By clicking the reCAPTCHA checkbox in Selenium
  • By adding a delay in your selenium script and manually solving Captcha while running.

Let’s understand these in a detailed manner.

Also read: What is Selenium?

How to disable Captchas in Test Environment?

The easiest and most foolproof way to handle captchas in Selenium is to disable the need for captchas during your test. By disabling captchas in test environments, you would no longer need to perform the Captcha task while testing a web application.

The disadvantage of this approach is that you are testing something different from your production environment. Ideally, you want your automated tests to test your product in an environment that resembles your production environment.

Disabling Captchas has now become very easy with Google’s open-source captcha widget called reCaptcha.

What is reCAPTCHA?

reCAPTCHA is a CAPTCHA system that enables web hosts to distinguish between human and automated access to websites. reCAPTCHA is a free service from Google and is very widely used nowadays 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.

reCAPTCHA v2

In case you are using reCAPTCHA v2, you can put the Site Key and Secret Key also known as the test keys. These keys help in bypassing the CAPTCHA verification request and as a result, your automation case can run seamlessly.

Below are the test keys for the same

  • Site Key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
  • Secret Key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

Once you enable the site keys you will see a warning message as shown below. This indicates that the CAPTCHA has been bypassed only for testing purposes and not in real-time.

Captcha In Selenium

reCAPTCHA v3

In the case of reCAPTCHA v3, the user needs to create their own keys for testing environments. Unlike reCAPTCHA v2, where the same keys are used for multiple environments, reCAPTCHA v3 enables the users to create separate keys for separate testing environments.

It is recommended to safeguard your code and credentials so that the test credentials can never be used in production mode. This must be done in order to avoid the risk of contaminating reCAPTCHA risk analysis with the data from the test environment, which can alter the test result analysis.

You can create your reCAPTCHA v3 keys from the Google reCAPTCHA website.

How to automate Captcha in Selenium WebDriver?

CAPTCHAs can be automated if you are able to decode the image using OCR (Optical Character Recognition). However, to do that, you’ll need to write complex algorithms to sort out the image pattern – and writing an algorithm is not that easy. Moreover, one has to be an expert in image pattern mapping as well.

But images, with time, have become progressively more unreadable, thereby reducing the chances of CAPTCHA automation.

That leaves us with one way to bypass the CAPTCHA, but it won’t automate it. In that case, we can tweak the script to wait for a certain interval of time at the screen where CAPTCHA is present, and the user will enter the CAPTCHA text himself, while other fields will be filled automatically.

Using this, we can achieve the target of complete web automation to a certain degree. But, this would still be a semi-automated test. In other scenarios, where we just have a reCAPTCHA checkbox, we can simply click it using Selenium.

Now we have seen how to automate Captcha in Selenium WebDriver. In the next section of this article on how to handle Captcha in Selenium, let us see both of these scenarios in our automation test.

By clicking the reCAPTCHA checkbox in Selenium

In case your application uses the reCAPTCHA checkbox, you will want to click the Captcha to complete the script. One of the mechanisms that reCaptcha uses is checking how long it took for the captcha to complete.

Humans will take a bit longer to complete a captcha task as compared to robots. Therefore, before clicking the Captcha, you will want to add a delay (for example using WebDriverWait) to replicate human behavior.

Also read: Types of Waits in Selenium

If you are wondering what is WebDriverWait in Selenium, let me share some insights on it. WebDriver equips the user with two kinds of waits in order to handle the recurring page loads, web element loads, the appearance of pop-ups and error messages, etc. on the web page. They are:

  • Implicit Wait
  • Explicit Wait

WebDriverWait falls under the category of Explicit Waits. Explicit Waits are used to halt the execution until the time a particular condition is met or the maximum time has elapsed. You will be able to understand it better once we use it in our implementation.

Let us now see the automation of Captchas using an example in Selenium. In the below example, we will automate the SIGN UP page of old.reddit.com.

We will make use of the LambdaTest cloud Selenium Grid to automate our test cases. LambdaTest is a cloud-based cross browser testing platform that supports Selenium Grid, providing a solution to overcome every challenge you might face while performing automation testing on your local machine. Selenium testing tools like LambdaTest offer a Selenium Grid consisting of 3000+ online browsers for you to perform Selenium automation testing effortlessly.

Use Case

  1. Launch the web browser.
  2. Open https://old.reddit.com/login.
  3. Enter username.
  4. Enter password.
  5. Enter the password again in Verify Password.
  6. Enter the email id
  7. Wait for the reCAPTCHA checkbox to appear.
  8. Click on it.

Below is the test class file which will help you to automate the checkbox. Here we have used Java with Selenium for automating Captcha in Selenium WebDriver.

If you’re a developer who’s looking to take your Java development and test engineering skills to the next level, this Selenium Java 101 certification from LambdaTest can help you reach that goal.

Here’s a short glimpse of the Selenium Java 101 certification from LambdaTest:

automateCaptchaInSelenium.java

You can use the below testng.xml file for running the class file.

Testng.xml

Below is the pom.xml file you will need to install the necessary dependencies.

Pom.xml

GitHub

Code Walkthrough

Let us now understand the different areas of code in detail.

  • Imported Dependencies: Here, we have imported all the necessary classes of Selenium WebDriver, WebDriverWait, Desired Capabilities, and RemoteWebDriver to set the respective browser capabilities and run the test cases on the grid.
  • Selenium And Captcha

  • Global Variables: As we have used a Selenium Grid Cloud like LambdaTest to perform our test execution, we are using the below-shown variables.

    Here, you can populate the values for your corresponding username and access key, which can be collected by logging into your LambdaTest Profile Section. You can copy the Username and the Access Token to be used in the code. However, the grid URL will remain the same, as shown below.

  • Selenium And Captcha Integration

  • @BeforeClass(Setup Method): Here, we have used the LambdaTest Desired Capabilities Generator and have set the necessary capabilities of browser name, version, platform, etc., for our Selenium Remote WebDriver. After that, we are opening the website in the launched browser.
  • Captcha For Selenium

  • @Test(clickOnRecaptchaCheckBoxInSelenium): In this case, we are locating the web elements for username and then entering the username value into it. Similarly, we are locating the corresponding web elements for the password, verify password, and email text boxes as shown in the below image.

    Reddit

    We are making use of XPaths in Selenium for locating each element. So, in order to locate the element and write its XPath, you can simply right-click on the web element and click on Inspect. Then, in the Elements tab, you can start writing the locator.

    Captcha Testing

    Once all the above elements have been located and their values are entered, we wait for the frame having the reCAPTCHA checkbox to be visible and switch to it. We achieve this by making use of WebDriverWait class and ExpectedConditions.ExpectedConditions in Selenium lets you wait for the occurrence of a specified condition before execution can proceed to the next step. If the condition is not met within the expected time duration, an appropriate exception is raised.

    Finally, when we have switched to the frame, we wait for the checkbox to be clickable and finally click on it. In case you are new to iFrames, you can check out the blog on handling iFrames in Selenium.

    Captcha For Selenium Testing

    Selenium And Captcha Guide

  • @AfterTest(closeBrowser): In this method, we are closing the browser that we had launched. Once the tests are completed, you can view the test results, logs, and the test recording as well in your LambdaTest Automation Dashboard.

    Automation Dashboard

    We saw how to click the reCAPTCHA checkbox in Selenium; however, if you are using Puppeteer or Playwright, you can open an URL containing the captcha and find the specific captcha DOM element, and click the Captcha.

    In order to see the Test Overview, you can navigate to the LambdaTest Analytics Dashboard. The Test Overview showcases the Test Case Health Snapshot for tests that consistently pass, consistently fail, etc. Test Summary, on the other hand, displays the total number of tests passed, failed, completed, etc.

    Automation Analytics Dashboard

Solving Captcha issues in Selenium

With this approach, your test will detect the Captcha and wait for a specific amount of time, allowing you to enter the correct captcha answer. While waiting for the captcha answer, you will need to manually look at the captcha question, solve the captcha and pass the answer to the (automated) test.

However, this option to handle Captcha in Selenium is not recommended, as it requires manual intervention during an automated test, and as a result, the test case is not 100% automated.

We can achieve it again by using WebDriverWait in Selenium and giving the user the time to solve the captcha manually. WebDriver will wait till the next action is ready.

We can see the same Use Case where once the reCAPTCHA checkbox has been clicked, we wait till the SIGN UP button gets enabled, and by the time the user gets the opportunity to solve the Captcha manually.

Captcha And Testing

Below is the test class file you can use to automate the scenario.

automateCaptchaInSelenium.java

GitHub

You can use the below testng.xml file for running the class file.

Testng.xml

Code Walkthrough

Here, everything remains the same as explained in the code walkthrough of our first example except the part where we wait for the SIGN UP button to be clickable after the checkbox has been clicked. Now, after the reCAPTCHA checkbox has been clicked, the screen selects the applicable images. Once that is done, the SIGN UP button gets clickable. Hence, when the user manually solves the captcha, the web driver waits for the SIGN UP button to get clickable.

Code For Captcha Testing

How to handle invisible reCaptcha in Selenium?

reCAPTCHA v2 offers an invisible captcha, which does not require the user to perform any interaction with the captcha. Unfortunately, the invisible captcha tries to block the web traffic that appears to come from a bot, so in order to avoid this, you can:

  • Change the user-agent of your test script.

How to change the user agent?

  • For Chrome

In case you are using the Chrome browser follow the below steps:

  1. First, you should add a User-Agent Switcher to your Chrome browser.
  2. Then, go to User-Agent Switcher settings at Chrome extensions section and get the desired agent’s information.

Selenium Test

Later, in your test script, you can make use of the ChromeOptions class and add the corresponding arguments as shown below in the Before Setup Method.

Also read – ChromeDriver in Selenium

  • For Firefox

In case you are using the Firefox browser follow the below steps.

  1. First, you should add User-Agent Switcher to your Firefox browser.
  2. Save all device lists to the desktop and import them as shown below.
  3. User agent Switcher

  4. Go to Tools-> Default User Agent -> Edit User Agents
  5. User agent Switching

  6. Then select Mobile Devices -> Devices -> HTC -> One M9 – Android 6.0 -Chrome 52.0 and then click Edit.

Switch User Agent

Then, you can see the user agent value of the HTC One M9 as shown below. Copy and save these values for user agent manipulation in our selenium web driver test automation code.

Later you can use the setPreference method in your BeforeSetup method with the general.useragent.override flag and pass the value you had collected in the previous step.

Also read – Adding Firefox Extensions in Selenium Python [Tutorial]

These were some of the ways of handling invisible reCAPTCHAs in Firefox and Chrome browsers.

Conclusion

We know that automating Captchas in Selenium is not one of the best practices. However, we might need to replicate our actual use case. In this article on how to handle Captcha in Selenium, we read what are Captchas and how we can deal with them in Selenium automation testing. We also read about reCAPCTHAs and how to disable them in testing environments, followed by how to automate Captcha in Selenium WebDriver. In the end, we also saw what Invisible Captchas are and how to handle them.

I hope you learned something new about Captchas in Selenium and enjoyed reading this blog.
Happy Testing!!

Frequently Asked Questions (FAQs)

Can we handle CAPTCHA in selenium?

The best practice for testing a web application is to disable Captcha in the testing environment. However, there are three ways you can handle Captcha in Selenium: by disabling the security check, writing code that clicks the ‘I’m not a robot’ checkbox, or by implementing a delay and solving Captcha while you test.

Can we automate reCaptcha?

Though it is not advisable to try on any CAPTCHA that uses a limited database if you still want to build software that auto-solves CAPTCHA, we would suggest you use other types of CAPTCHA rather than reCAPTCHA.

Can I bypass CAPTCHA?

Yes. Completing a CAPTCHA is required to prove you are a human, but there are ways that an evil bot can beat the system.

Written by

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *