ProxyForge Download

Captcha Solving in Python: 2captcha, CapSolver, and Proxy Integration

Captcha Solving in Python: 2Captcha, CapSolver, and Proxy Integration

Introduction

CAPTCHA systems are designed to distinguish between human users and automated scripts. They present challenges that are easy for humans to solve but difficult or impossible for bots. This is a significant hurdle for developers working on projects involving web scraping, automation, or any service where user interaction is required programmatically. In this guide, we'll explore how CAPTCHA-as-a-service providers like 2captcha and CapSolver work, their integration into Python applications, and the importance of using residential proxies to maintain anonymity.

Understanding CAPTCHA as a Service

Human Solver Farms vs AI

CAPTCHA solving services operate by distributing CAPTCHAs to human workers or automated systems. Traditional human solver farms employ individuals who manually solve CAPTCHAs in exchange for payment, ensuring a high success rate but at the cost of speed and reliability.

AI-based solutions, on the other hand, use machine learning algorithms to recognize patterns in CAPTCHAs. While faster and more reliable than human solvers, they may not always succeed due to the evolving nature of CAPTCHA design.

2captcha: How It Works

2captcha is a popular CAPTCHA-solving service that provides an API for integrating with your Python application. The process involves three main steps:

Here’s a simple example using Python:

import requests
import time

def solve_captcha(api_key, captcha_type, sitekey):
    url = "https://2captcha.com/in.php"
    payload = {
        'key': api_key,
        'method': captcha_type,
        'googlekey': sitekey,
        'pageurl': 'http://example.com'
    }
    
    # Submit CAPTCHA
    response = requests.post(url, data=payload)
    captcha_id = response.text.split('|')[1]

    if captcha_id == 'ERROR_ZERO_BALANCE':
        print("Error: Your balance is zero.")
        return None

    # Poll for solution
    while True:
        result_url = f"https://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}"
        response = requests.get(result_url)
        
        if 'OK' in response.text:
            token = response.text.split('|')[1]
            print("CAPTCHA solved successfully.")
            return token
        elif 'ERROR_CAPTCHA_UNSOLVABLE' in response.text:
            print("Error: CAPTCHA could not be solved.")
            return None
        
        time.sleep(5)  # Wait for the CAPTCHA to be solved

# Example usage
api_key = "your_2captcha_api_key"
sitekey = "your_sitekey"
token = solve_captcha(api_key, 'userrecaptcha', sitekey)
if token:
    print(f"Solved token: {token}")

CapSolver for hCaptcha and Turnstile

CapSolver is another CAPTCHA-solving service that supports various CAPTCHA types including hCaptcha and Turnstile. It uses a combination of human solvers and AI to provide reliable solutions.

To integrate CapSolver, you need to:

Here’s a basic example:

import requests

def solve_captcha(api_key, captcha_type, sitekey):
    url = "https://api.capsolver.com/solve"
    payload = {
        'clientKey': api_key,
        'task': {
            'type': captcha_type,
            'websiteURL': 'http://example.com',
            'websiteKey': sitekey
        }
    }

    # Submit CAPTCHA
    response = requests.post(url, json=payload)
    task_id = response.json().get('taskId')

    if not task_id:
        print("Error submitting CAPTCHA.")
        return None

    # Poll for solution
    while True:
        status_url = "https://api.capsolver.com/getTaskResult"
        payload = {'clientKey': api_key, 'taskId': task_id}
        response = requests.post(status_url, json=payload)
        
        if response.json().get('status') == 'ready':
            token = response.json().get('solution').get('gRecaptchaResponse')
            print("CAPTCHA solved successfully.")
            return token
        elif response.json().get('errorId'):
            print(f"Error: {response.json().get('errorCode')} - {response.json().get('errorMessage')}")
            return None
        
        time.sleep(5)  # Wait for the CAPTCHA to be solved

# Example usage
api_key = "your_capsolver_api_key"
sitekey = "your_sitekey"
token = solve_captcha(api_key, 'HCaptchaTask', sitekey)
if token:
    print(f"Solved token: {token}")

Cost Comparison and Pricing Models

Both 2captcha and CapSolver offer competitive pricing models, typically ranging from $1-3 per 1000 CAPTCHA solves. The cost depends on the type of CAPTCHA, the volume of requests, and the success rate.

Proxy Integration

Using residential proxies ensures that the same IP address submits the CAPTCHA token, which can help bypass some anti-bot mechanisms. Popular providers include:

Here’s how you can integrate a proxy with your CAPTCHA solving requests using Python's requests library:

import requests

def solve_captcha_with_proxy(api_key, captcha_type, sitekey, proxy):
    url = "https://2captcha.com/in.php"
    payload = {
        'key': api_key,
        'method': captcha_type,
        'googlekey': sitekey,
        'pageurl': 'http://example.com'
    }
    
    # Submit CAPTCHA with proxy
    proxies = {
        'http': f'http://{proxy}',
        'https': f'https://{proxy}'
    }
    response = requests.post(url, data=payload, proxies=proxies)
    captcha_id = response.text.split('|')[1]

    if captcha_id == 'ERROR_ZERO_BALANCE':
        print("Error: Your balance is zero.")
        return None

    # Poll for solution with proxy
    while True:
        result_url = f"https://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}"
        response = requests.get(result_url, proxies=proxies)
        
        if 'OK' in response.text:
            token = response.text.split('|')[1]
            print("CAPTCHA solved successfully.")
            return token
        elif 'ERROR_CAPTCHA_UNSOLVABLE' in response.text:
            print("Error: CAPTCHA could not be solved.")
            return None
        
        time.sleep(5)  # Wait for the CAPTCHA to be solved

# Example usage
api_key = "your_2captcha_api_key"
sitekey = "your_sitekey"
proxy = "your_proxy_ip:port"
token = solve_captcha_with_proxy(api_key, 'userrecaptcha', sitekey, proxy)
if token:
    print(f"Solved token: {token}")

Handling CAPTCHAs in Different Phases

CAPTCHAs can appear during different phases of a web page load:

It’s essential to handle both scenarios in your Python scripts to ensure reliable bypassing of CAPTCHAs.

Async Integration for High-Volume Scraping

For high-volume scraping tasks, asynchronous processing can significantly improve performance. Using libraries like aiohttp and asyncio, you can manage multiple CAPTCHA solving requests concurrently.

Here’s a basic example using aiohttp:

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →