How to Solve Captcha in Selenium with Python: A Comprehensive Guide

CAPTCHAFORUM

Administrator
1733328162145.png


Automation testing with Selenium is powerful, but it often encounters challenges, such as captchas, designed to prevent bots from interacting with websites. However, with the help of services like 2Captcha, solving captchas in Selenium is not only possible but also efficient. This guide will walk you through the process of solving captchas in Python using Selenium and 2Captcha.

What is a Captcha?​

A CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a security feature used to distinguish between human users and automated bots. Captchas include:
  • Image Captchas: Identify objects in images.
  • ReCaptcha v2/v3: Tick boxes or invisible scoring.
  • hCaptcha: Similar to ReCaptcha but with different challenges.
  • Text Captchas: Enter distorted characters displayed in an image.

Why Use 2Captcha?​

2Captcha is a popular captcha-solving service that uses human workers to solve challenges. Here’s why it’s highly recommended:
  1. Wide Support: Works with image, ReCaptcha, hCaptcha, and more.
  2. Speed: Provides solutions quickly.
  3. Accuracy: Human solvers ensure higher success rates.
  4. Affordable: Flexible pricing for small and large-scale projects.
  5. Easy Integration: Includes APIs and libraries for seamless integration.

Setting Up the Environment​

Before diving into captcha solving, ensure you have the following tools installed:
  1. Python (3.x)
  2. Selenium: For web automation.
  3. 2Captcha API Key: Sign up at 2Captcha and obtain your API key.
  4. WebDriver: Compatible with your browser (e.g., ChromeDriver).
Install necessary Python libraries:

Code:
pip install selenium requests

Solving Captchas in Selenium with 2Captcha​

Step 1: Automating Web Navigation with Selenium​

First, use Selenium to navigate to the webpage with the captcha. Here’s an example:

Code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

# Setup WebDriver
driver = webdriver.Chrome()
driver.get("https://example.com/captcha")

# Interact with elements before captcha if required
input_field = driver.find_element(By.ID, "username")
input_field.send_keys("your_username")

Step 2: Capturing the Captcha​

If it’s an image-based captcha, download the captcha image:

Code:
captcha_image = driver.find_element(By.ID, "captchaImage")
captcha_image.screenshot("captcha.png")  # Save captcha image locally

Step 3: Sending the Captcha to 2Captcha​

To send the captcha to 2Captcha, use their API.

Code:
import requests

API_KEY = "your_2captcha_api_key"  # Replace with your API key

# Upload captcha to 2Captcha
with open("captcha.png", "rb") as captcha_file:
    response = requests.post(
        "http://2captcha.com/in.php",
        files={"file": captcha_file},
        data={"key": API_KEY, "method": "post"}
    )

captcha_id = response.text.split("|")[1]  # Extract captcha ID

Step 4: Retrieving the Solution​

Poll 2Captcha for the solution using the captcha ID:

Code:
import time

# Wait for the solution
while True:
    response = requests.get(
        f"http://2captcha.com/res.php?key={API_KEY}&action=get&id={captcha_id}"
    )
    if "OK" in response.text:
        captcha_solution = response.text.split("|")[1]
        break
    time.sleep(5)  # Retry after 5 seconds

Step 5: Submitting the Captcha Solution​

Use the solution provided by 2Captcha to complete the form:

Code:
captcha_field = driver.find_element(By.ID, "captchaField")
captcha_field.send_keys(captcha_solution)
captcha_field.send_keys(Keys.RETURN)  # Submit the form

Solving ReCaptcha with 2Captcha​

ReCaptcha challenges (v2 and v3) require special handling. Thankfully, 2Captcha simplifies this with its ReCaptcha solving method.

Here’s how to solve a ReCaptcha v2:

Code:
SITE_KEY = "your_recaptcha_site_key"  # Found in the site's HTML
PAGE_URL = driver.current_url

# Send ReCaptcha solving request
response = requests.get(
    "http://2captcha.com/in.php",
    params={
        "key": API_KEY,
        "method": "userrecaptcha",
        "googlekey": SITE_KEY,
        "pageurl": PAGE_URL
    }
)
captcha_id = response.text.split("|")[1]

# Retrieve the solution
while True:
    response = requests.get(
        f"http://2captcha.com/res.php?key={API_KEY}&action=get&id={captcha_id}"
    )
    if "OK" in response.text:
        recaptcha_response = response.text.split("|")[1]
        break
    time.sleep(5)

# Inject the solution into the ReCaptcha field
driver.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML='{recaptcha_response}';")
driver.find_element(By.ID, "submit-button").click()

With the powerful combination of Selenium and 2Captcha, automating captcha-solving becomes straightforward. Whether you're dealing with image-based captchas or ReCaptcha challenges, 2Captcha’s robust API ensures high accuracy and speed.

By leveraging 2Captcha, you can save significant time and effort, focusing on your automation goals without worrying about captcha roadblocks. Start your automation journey today with 2Captcha and experience hassle-free captcha solving!