2captcha-python

repository·master·Indexed 21 days ago

https://github.com/2captcha/2captcha-python

A Python client for the 2Captcha API used to automate the solving of various captcha types, including reCAPTCHA, FunCaptcha, GeeTest, Cloudflare Turnstile, and Amazon WAF. It provides both synchronous (TwoCaptcha) and asynchronous (AsyncTwoCaptcha) implementations, supporting image-based, audio, and text CAPTCHAs, as well as specialized interaction types like grid, canvas, and rotation.

Tokens
5.3K
Snippets
16
Records
17
Agent score
23%

What's inside 2captcha-python

  1. Configure the TwoCaptcha instance

    master

    To use the library, initialize a TwoCaptcha instance with your API key. You can also use AsyncTwoCaptcha for asynchronous operations.

    For advanced configuration, pass a dictionary of options to the constructor using keyword arguments.

    from twocaptcha import TwoCaptcha
    
    solver = TwoCaptcha('YOUR_API_KEY')
  2. Configure proxies for captcha solving

    master

    You can pass a proxy dictionary as an additional argument to several methods (including recaptcha, funcaptcha, geetest, turnstile, amazon waf, etc.) to have the proxy forwarded to the API.

    The proxy dictionary should follow this format:

    proxy={
        'type': 'HTTPS', # or other supported types
        'uri': 'login:password@IP_address:PORT'
    }
  3. Configure TwoCaptcha instance options

    master

    The TwoCaptcha constructor accepts several configuration options to customize API behavior, timeouts, and result handling:

    OptionDefaultDescription
    server2captcha.comAPI server. Use rucaptcha.com if your account is registered there.
    softId4580Your software ID from the 2captcha software catalog.
    callback-URL of your web server to receive results. Note: If set, methods return only the captcha ID and stop polling; results are sent to your URL instead.
    defaultTimeout120Polling timeout in seconds for all captcha types except reCAPTCHA.
    recaptchaTimeout600Polling timeout in seconds specifically for reCAPTCHA.
    pollingInterval10Interval in seconds between requests to the API. Values < 5s are not recommended.
    extendedResponseNoneSet to True to enable JSON responses from the API. Useful for ClickCaptcha and Canvas.
    config = {
        'server':           '2captcha.com',
        'apiKey':           'YOUR_API_KEY',
        'softId':            123,
        'callback':         'https://your.site/result-receiver',
        'defaultTimeout':    120,
        'recaptchaTimeout':  600,
        'pollingInterval':   10,
        'extendedResponse':  False
    }
    solver = TwoCaptcha(**config)
  4. Handle captcha solver exceptions

    master

    The solver throws specific exceptions when errors occur. It is recommended to wrap calls in a try...except block to handle these cases:

    • ValidationException: Invalid parameters were passed.
    • NetworkException: A network error occurred.
    • ApiException: The API responded with an error.
    • TimeoutException: The captcha has not been solved within the expected timeframe.
    try:
        result = solver.text('If tomorrow is Saturday, what day is today?')
    except ValidationException as e:
        # invalid parameters passed
        print(e)
    except NetworkException as e:
        # network error occurred
        print(e)
    except ApiException as e:
        # api respond with error
        print(e)
    except TimeoutException as e:
        # captcha is not solved so far
        print(e)
  5. Solve multiple captchas in parallel using asyncio

    master

    The AsyncTwoCaptcha class allows you to solve multiple captchas concurrently using asyncio.gather, which is significantly faster than solving them sequentially.

    async def solve_multiple_captchas():
        solver = AsyncTwoCaptcha('YOUR_API_KEY')
        
        # Start all tasks simultaneously
        task1 = asyncio.create_task(solver.text('What color is the sky on a clear day?'))
        task2 = asyncio.create_task(solver.text('What is 2+2?'))
        task3 = asyncio.create_task(solver.text('Name of the planet we live on?'))
        
        # Wait for all tasks to complete
        results = await asyncio.gather(task1, task2, task3, return_exceptions=True)
        return results
    
    # This completes much faster than solving captchas sequentially
    results = asyncio.run(solve_multiple_captchas())
  6. Use legacy executor-based async approach

    master

    For backward compatibility, you can run the synchronous TwoCaptcha client within a thread pool using loop.run_in_executor.

    import asyncio
    import concurrent.futures
    from twocaptcha import TwoCaptcha
    
    API_KEY = "YOUR_API_KEY"
    image = "data:image/png;base64,iVBORw0KGgoA..."
    
    async def captchaSolver(image):
        loop = asyncio.get_running_loop()
        with concurrent.futures.ThreadPoolExecutor() as pool:
            result = await loop.run_in_executor(pool, lambda: TwoCaptcha(API_KEY).normal(image))
            return result
    
    captcha_result = asyncio.run(captchaSolver(image))
  7. Solve FunCaptcha, GeeTest, and Lemin CAPTCHAs

    master

    Various specialized methods exist for different providers:

    • solver.funcaptcha(): Returns a token for Arkoselabs FunCaptcha.
    • solver.geetest(): Returns a set of tokens as JSON for GeeTest puzzle CAPTCHAs.
    • solver.geetest_v4(): Returns JSON for GeeTest v4.
    • solver.lemin(): Returns JSON containing answer and challenge_id for Lemin Cropped CAPTCHAs.
    # FunCaptcha
    result = solver.funcaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                                url='https://mysite.com/page/with/funcaptcha',
                                param1=..., ...)
    
    # GeeTest
    result = solver.geetest(gt='f1ab2cdefa3456789012345b6c78d90e',
                            challenge='12345678abc90123d45678ef90123a456b',
                            url='https://www.site.com/page/',
                            param1=..., ...)
    
    # Lemin Cropped Captcha
    result = solver.lemin(captcha_id='CROPPED_1abcd2f_a1234b567c890d12ef3a456bc78d901d',
                            div_id='lemin-cropped-captcha', 
                            url='https://www.site.com/page/',
                            param1=..., ...)
  8. Solve reCAPTCHA v2 and v3

    master

    Use solver.recaptcha() to solve reCAPTCHA. For v2, provide the sitekey and url. For v3, provide the sitekey, url, and set version='v3'.

    # reCAPTCHA v2
    result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                              url='https://mysite.com/page/with/recaptcha',
                              param1=..., ...)
    
    # reCAPTCHA v3
    result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                                url='https://mysite.com/page/with/recaptcha',
                                version='v3',
                                param1=..., ...)
  9. Solve Normal, Audio, and Text CAPTCHAs

    master

    Use solver.normal() for distorted text on images (supports local paths or URLs). Use solver.audio() for MP3 audio CAPTCHAs (requires lang parameter with values like 'en', 'ru', 'de', 'el', 'pt', 'fr'). Use solver.text() for CAPTCHAs that present a clear text question.

    # Normal Captcha
    result = solver.normal('path/to/captcha.jpg', param1=..., ...)
    # OR
    result = solver.normal('https://site-with-captcha.com/path/to/captcha.jpg', param1=..., ...)
    
    # Audio Captcha
    result = solver.audio('path/to/captcha.mp3', lang = 'en', param1=..., ...)
    
    # Text Captcha
    result = solver.text('If tomorrow is Saturday, what day is today?', param1=..., ...)
  10. Manually submit and poll captcha results with send/get_result

    master

    For custom captcha types not covered by dedicated methods, use send() to submit the captcha and get_result() to poll for the answer. When using send(), you must manually specify the method parameter (e.g., method='recaptcha') based on the 2Captcha API documentation.

    import time
    
    # Example for solving Normal captcha manually
    id = solver.send(file='path/to/captcha.jpg')
    time.sleep(20)
    
    code = solver.get_result(id)
  11. Use AsyncTwoCaptcha for asynchronous solving

    master

    To perform non-blocking captcha solving, use the AsyncTwoCaptcha class. It supports all the same methods and parameters as the synchronous TwoCaptcha class but requires await for method calls.

    import asyncio
    from twocaptcha import AsyncTwoCaptcha
    
    async def solve_captcha():
        solver = AsyncTwoCaptcha('YOUR_API_KEY')
        
        try:
            recaptcha_result = await solver.recaptcha(...)
            return recaptcha_result
        except Exception as e:
            print(e)
            return None
    
    if __name__ == '__main__':
        result = asyncio.run(solve_captcha())