CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-2captcha-python

Python module for easy integration with 2Captcha API service to solve various types of captchas including reCAPTCHA, FunCaptcha, GeeTest, and many others

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

audio-text-captchas.mddocs/

Audio and Text Captchas

Methods for solving non-visual captcha challenges including audio captchas and text-based questions that require human reasoning or reading comprehension.

Capabilities

Audio Captcha

Solves audio captchas where users must transcribe spoken words or numbers from audio files.

def audio(self, file, lang, **kwargs):
    """
    Solve audio captcha challenges.
    
    Parameters:
    - file (str): Path to MP3 audio file, URL to MP3 file, or base64-encoded MP3 data (required, max 1MB)
    - lang (str): Audio language code - must be one of: "en", "ru", "de", "el", "pt", "fr" (required)
    - softId (int): Software developer ID
    - callback (str): Pingback URL for result notification
    
    Returns:
    dict: {'captchaId': str, 'code': str} - code contains transcribed text
    
    Raises:
    ValidationException: If file is None, invalid format, or unsupported language
    """

Text Captcha

Solves text-based captcha questions that require human reasoning, reading comprehension, or knowledge.

def text(self, text, **kwargs):
    """
    Solve text-based captcha questions.
    
    Parameters:
    - text (str): The question or instruction text (required, max 140 characters, UTF-8)
    - lang (str): Language code for the question (optional, see 2captcha.com language list)
    - softId (int): Software developer ID
    - callback (str): Pingback URL for result notification
    
    Returns:
    dict: {'captchaId': str, 'code': str} - code contains the answer
    """

Usage Examples

Audio Captcha from File

from twocaptcha import TwoCaptcha, ValidationException

solver = TwoCaptcha('your_api_key')

# Solve audio captcha from local file
try:
    result = solver.audio(
        file='path/to/audio_captcha.mp3',
        lang='en'
    )
    print(f"Audio transcription: {result['code']}")
except ValidationException as e:
    print(f"File error: {e}")

# Solve with different languages
languages = ['en', 'ru', 'de', 'fr', 'pt', 'el']
for lang in languages:
    try:
        result = solver.audio(f'audio_{lang}.mp3', lang)
        print(f"{lang.upper()}: {result['code']}")
    except Exception as e:
        print(f"Error with {lang}: {e}")

Audio Captcha from URL

from twocaptcha import TwoCaptcha

solver = TwoCaptcha('your_api_key')

# Solve audio captcha from URL
result = solver.audio(
    file='https://example.com/audio_captcha.mp3',
    lang='en'
)
print(f"URL audio solved: {result['code']}")

# Handle download errors
try:
    result = solver.audio(
        file='https://invalid-url.com/missing.mp3',
        lang='en'
    )
except ValidationException as e:
    print(f"Download failed: {e}")

Audio Captcha from Base64

from twocaptcha import TwoCaptcha
import base64

solver = TwoCaptcha('your_api_key')

# Read and encode audio file
with open('audio_captcha.mp3', 'rb') as audio_file:
    audio_data = audio_file.read()
    audio_base64 = base64.b64encode(audio_data).decode('utf-8')

# Solve from base64 data
result = solver.audio(
    file=audio_base64,
    lang='en'
)
print(f"Base64 audio solved: {result['code']}")

Text Captcha Questions

from twocaptcha import TwoCaptcha

solver = TwoCaptcha('your_api_key')

# Simple math question
result = solver.text('What is 2 + 2?')
print(f"Math answer: {result['code']}")

# Reading comprehension
result = solver.text(
    text='If it is raining, I will stay home. It is raining. Will I go out?',
    lang='en'
)
print(f"Logic answer: {result['code']}")

# Color/visual description
result = solver.text('What color do you get when you mix red and blue?')
print(f"Color answer: {result['code']}")

# Common knowledge
result = solver.text('What is the capital of France?')
print(f"Geography answer: {result['code']}")

Multilingual Text Captchas

from twocaptcha import TwoCaptcha

solver = TwoCaptcha('your_api_key')

# Russian text captcha
result = solver.text(
    text='Сколько будет 5 + 3?',
    lang='ru'
)
print(f"Russian math: {result['code']}")

# German text captcha
result = solver.text(
    text='Wie viele Tage hat eine Woche?',
    lang='de'
)
print(f"German question: {result['code']}")

# French text captcha  
result = solver.text(
    text='Combien font 10 - 4?',
    lang='fr'
)
print(f"French math: {result['code']}")

Audio Processing with Error Handling

from twocaptcha import TwoCaptcha, ValidationException
import os

solver = TwoCaptcha('your_api_key')

def solve_audio_with_validation(file_path, language):
    """Solve audio captcha with comprehensive error handling"""
    
    # Validate file exists
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"Audio file not found: {file_path}")
    
    # Validate file size (2captcha has 1MB limit)
    file_size = os.path.getsize(file_path)
    if file_size > 1024 * 1024:  # 1MB
        raise ValueError(f"File too large: {file_size} bytes (max 1MB)")
    
    # Validate language
    supported_langs = ['en', 'ru', 'de', 'el', 'pt', 'fr']
    if language not in supported_langs:
        raise ValueError(f"Unsupported language: {language}. Use: {supported_langs}")
    
    try:
        result = solver.audio(file_path, language)
        return result['code']
    except ValidationException as e:
        if 'not .mp3' in str(e):
            raise ValueError("File must be in MP3 format")
        elif 'File could not be downloaded' in str(e):
            raise ValueError("Could not access the audio file")
        else:
            raise

# Usage with validation
try:
    transcription = solve_audio_with_validation('audio.mp3', 'en')
    print(f"Transcription: {transcription}")
except (FileNotFoundError, ValueError, ValidationException) as e:
    print(f"Error: {e}")

Text Captcha with Length Validation

from twocaptcha import TwoCaptcha

solver = TwoCaptcha('your_api_key')

def solve_text_captcha(question, lang='en'):
    """Solve text captcha with input validation"""
    
    # Validate text length (140 char limit)
    if len(question) > 140:
        raise ValueError(f"Question too long: {len(question)} chars (max 140)")
    
    # Validate UTF-8 encoding
    try:
        question.encode('utf-8')
    except UnicodeEncodeError:
        raise ValueError("Question contains invalid UTF-8 characters")
    
    result = solver.text(text=question, lang=lang)
    return result['code']

# Test with various questions
questions = [
    "What is 7 * 8?",
    "Name a fruit that is red",
    "How many legs does a spider have?",
    "What comes after Wednesday?",
    "What is the opposite of hot?"
]

for question in questions:
    try:
        answer = solve_text_captcha(question)
        print(f"Q: {question}")
        print(f"A: {answer}\n")
    except Exception as e:
        print(f"Error with '{question}': {e}\n")

Integration with Web Scraping

from twocaptcha import TwoCaptcha
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
import os

solver = TwoCaptcha('your_api_key')

def handle_audio_captcha_on_page():
    """Handle audio captcha during web scraping"""
    
    driver = webdriver.Chrome()
    
    try:
        driver.get('https://site-with-audio-captcha.com/form')
        
        # Find audio captcha element
        audio_element = driver.find_element(By.CSS_SELECTOR, 'audio source')
        audio_url = audio_element.get_attribute('src')
        
        # Download audio file
        response = requests.get(audio_url)
        audio_path = 'temp_audio.mp3'
        
        with open(audio_path, 'wb') as f:
            f.write(response.content)
        
        # Solve audio captcha
        result = solver.audio(audio_path, 'en')
        
        # Enter solution
        audio_input = driver.find_element(By.NAME, 'audio_response')
        audio_input.send_keys(result['code'])
        
        # Submit form
        submit_btn = driver.find_element(By.CSS_SELECTOR, 'input[type="submit"]')
        submit_btn.click()
        
        print(f"Audio captcha solved: {result['code']}")
        
    finally:
        # Cleanup
        if os.path.exists('temp_audio.mp3'):
            os.remove('temp_audio.mp3')
        driver.quit()

# Usage
handle_audio_captcha_on_page()

Batch Processing Audio Captchas

from twocaptcha import TwoCaptcha
import os
import concurrent.futures

solver = TwoCaptcha('your_api_key')

def solve_single_audio(file_path, lang):
    """Solve single audio captcha"""
    try:
        result = solver.audio(file_path, lang)
        return (file_path, result['code'], None)
    except Exception as e:
        return (file_path, None, str(e))

def batch_solve_audio_captchas(audio_directory, language='en', max_workers=3):
    """Solve multiple audio captchas concurrently"""
    
    # Get all MP3 files
    audio_files = [
        os.path.join(audio_directory, f) 
        for f in os.listdir(audio_directory) 
        if f.endswith('.mp3')
    ]
    
    results = []
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        # Submit all tasks
        futures = [
            executor.submit(solve_single_audio, file_path, language)
            for file_path in audio_files
        ]
        
        # Collect results
        for future in concurrent.futures.as_completed(futures):
            file_path, transcription, error = future.result()
            results.append({
                'file': os.path.basename(file_path),
                'transcription': transcription,
                'error': error
            })
    
    return results

# Usage
results = batch_solve_audio_captchas('./audio_captchas/', 'en')

for result in results:
    if result['error']:
        print(f"Error with {result['file']}: {result['error']}")
    else:
        print(f"{result['file']}: {result['transcription']}")

Install with Tessl CLI

npx tessl i tessl/pypi-2captcha-python

docs

audio-text-captchas.md

cloud-captchas.md

core-solver.md

emerging-captchas.md

image-captchas.md

index.md

interactive-captchas.md

specialized-captchas.md

tile.json