How to bypass captcha using Selenium in Python
The article describes approaches to bypassing CAPTCHA using Selenium. A separate section contains links to working code examples for different types of CAPTCHA.
Selenium CAPTCHA Handling: Step-By-Step
The secret to conquering CAPTCHAs lies in making your script indistinguishable from a real human—think natural interactions and a convincing browser fingerprint. Enter Selenium, the go-to tool for developers seeking seamless browser automation. Pair it with 2Captcha, and you’ve got a powerhouse combo to tackle reCAPTCHAs, image CAPTCHAs, and more with ease.
In this part of the tutorial, you’ll discover how to dodge CAPTCHAs in Selenium using Python. Ready to make your script smarter? Let’s dive in!
Step #1: Set Up Your Python Project
Before diving into the world of CAPTCHA bypassing, ensure you have the following prerequisites ready:
- Python 3 installed on your system.
- Google Chrome browser available locally for testing.
If you already have a working Selenium web scraping or testing script, feel free to skip the setup steps. Otherwise, let’s build your project from scratch!
Open your terminal and run the following commands:
mkdir selenium_captcha_demo
cd selenium_captcha_demo
Add a new Python virtual environment inside it:
python3 -m venv venv
source venv/bin/activate # For macOS/Linux
venv\Scripts\activate # For Windows
Open the project’s folder in your favorite Python IDE and create a new file named script.py.
Step #2: Install Selenium
First, activate the virtual environment you created earlier. Use the following command based on your operating system:
For Windows:
venv\Scripts\activate
For Linux/macOS:
source venv/bin/activate
Next, install Selenium using pip
, Python’s package manager.
Run this command in your terminal:
pip install selenium
The installation process may take a few moments, so sit back and let it complete. You’ll soon have Selenium ready to power your automation script.
Step #3: Set Up Your Selenium Script
Set up a Selenium WebDriver instance in headless mode:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
# Close the browser after tasks
driver.quit()
Not sure what headless mode is? It’s a way to run browsers programmatically without displaying their UI, making it perfect for automated tasks. You can explore more in guide on headless browsers.
Use the configured options to start a Chrome WebDriver instance.
Step #4: Solve CAPTCHAs With 2Captcha
Integrate 2Captcha into your Selenium script to handle CAPTCHA challenges seamlessly.
Part 1: Sending CAPTCHA to 2Captcha
from selenium import webdriver
import requests
import time
# Set up Selenium WebDriver
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
driver.get("https://example.com")
# Extract CAPTCHA site key
captcha_site_key = driver.execute_script("return document.querySelector('[data-sitekey]').getAttribute('data-sitekey')")
API_KEY = "your_2captcha_api_key"
response = requests.post("http://2captcha.com/in.php", data={
"key": API_KEY,
"method": "userrecaptcha",
"googlekey": captcha_site_key,
"pageurl": "https://example.com"
})
captcha_id = response.text.split('|')[1]
print("Waiting for CAPTCHA solution...")
Part 2: Retrieving and Using the Solution
# Wait for the solution
time.sleep(20)
result = requests.get(f"http://2captcha.com/res.php?key={API_KEY}&action=get&id={captcha_id}")
while "CAPCHA_NOT_READY" in result.text:
time.sleep(5)
result = requests.get(f"http://2captcha.com/res.php?key={API_KEY}&action=get&id={captcha_id}")
# Inject the solution
captcha_solution = result.text.split('|')[1]
driver.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML = '{captcha_solution}';")
driver.find_element("id", "submit_button").click()
driver.quit()
Step #5: Enhance With Selenium Stealth
Selenium Stealth is a Python package that makes Selenium-controlled browsers mimic real ones, reducing bot detection by hiding automation traces. It's a Python equivalent to Puppeteer Stealth for bypassing anti-bot mechanisms.
If you’re familiar with anti-bot solutions, think of this as a Python alternative to Puppeteer Stealth.
Install Selenium Stealth
Use pip
to add the library to your project:
pip install selenium-stealth
Import Selenium Stealth
Include the library in your script by adding the following line to your script.py
:
from selenium_stealth import stealth
What’s Next?
With the library installed and imported, the final step is to configure the stealth settings to enhance your browser’s invisibility. Let’s proceed!
Step #6: Configure Stealth Settings to Avoid CAPTCHAs
To enable Selenium Stealth and configure Chrome WebDriver to bypass CAPTCHAs, use the stealth() function as shown:
stealth(
driver,
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win32",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
Feel free to adjust these arguments, but the provided values are sufficient to bypass most anti-bot systems.
Great work! Your Selenium-controlled browser now looks and behaves like a real browser used by a human.
Ready-to-Use Python + Selenium Examples
To help you get started quickly, we provide several ready-to-use examples demonstrating how to solve captchas with Python and Selenium:
-
Main Example Repository
A collection of examples for solving different types of captchas using Python and Selenium:
https://github.com/2captcha/captcha-solver-selenium-python-examples -
Grid-Based reCAPTCHA Solver
If you're working with Selenium Grid, check out this dedicated example for solving reCAPTCHA using the Grid method:
https://github.com/2captcha/selenium-recaptcha-solver-using-grid -
Additional Examples in the SDK Repository
If the above repositories don’t fit your needs, explore theexamples
directory in the official2captcha-python
SDK repository:
https://github.com/2captcha/2captcha-python/tree/master/examples
Solving Captchas Using the 2Captcha API and Selenium in Other Languages
The 2Captcha API supports integration with Selenium in various programming languages. Below are links to documentation and modules for the most popular languages:
-
JavaScript
Selenium Documentation: https://www.selenium.dev/selenium/docs/api/javascript/
2Captcha Module: https://github.com/2captcha/2captcha-javascript -
Python
Selenium Documentation: https://www.selenium.dev/selenium/docs/api/py/api.html
2Captcha Module: https://github.com/2captcha/2captcha-python
Examples: https://github.com/2captcha/captcha-solver-selenium-python-examples -
Java
Selenium Documentation: https://www.selenium.dev/selenium/docs/api/java/index.html
2Captcha Module: https://github.com/2captcha/2captcha-java -
C#
Selenium Documentation: https://www.selenium.dev/selenium/docs/api/dotnet/
2Captcha Module: https://github.com/2captcha/2captcha-csharp -
Ruby
Selenium Documentation: https://www.selenium.dev/selenium/docs/api/rb/
2Captcha Module: https://github.com/2captcha/2captcha-ruby
Conclusion
CAPTCHAs can feel like an insurmountable barrier, but with the right tools, they’re nothing more than a minor speed bump. While Selenium Stealth helps disguise automation, advanced CAPTCHA systems require a smarter, more efficient solution.
That’s where 2Captcha comes in. With our dedicated CAPTCHA-solving service, you can effortlessly handle reCAPTCHA, captcha, image CAPTCHAs, and many more. Whether you’re using Selenium or any other automation tool, our service integrates seamlessly, ensuring smooth and reliable CAPTCHA bypassing every time.
Don’t let CAPTCHAs slow you down—try 2Captcha today and experience effortless automation like never before!