Skip to main content

Python Module for 2Captcha API (captcha solver)

The easiest way to quickly integrate the 2Captcha captcha-solving service into your code and automate the solving of any type of captcha. Examples of API requests for different captcha types are available on the Python captcha solver page.

Installation

This package can be installed with Pip:

pip3 install 2captcha-python

Configuration

TwoCaptcha instance can be created like this:

from twocaptcha import TwoCaptcha

solver = TwoCaptcha('YOUR_API_KEY')
Async
from twocaptcha import AsyncTwoCaptcha

solver = AsyncTwoCaptcha('YOUR_API_KEY')

Also, there are a few options that can be configured:

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)

TwoCaptcha instance options

Option Default value Description
server 2captcha.com API server. You can set it to rucaptcha.com if your account is registered there
softId 4580 your software ID obtained after publishing in 2captcha software catalog
callback - URL of your web server that receives the captcha recognition result. The URL should be first registered in pingback settings of your account
defaultTimeout 120 Polling timeout in seconds for all captcha types except reCAPTCHA. Defines how long the module tries to get the answer from the res.php API endpoint
recaptchaTimeout 600 Polling timeout for reCAPTCHA in seconds. Defines how long the module tries to get the answer from the res.php API endpoint
pollingInterval 10 Interval in seconds between requests to the res.php API endpoint. Setting values less than 5 seconds is not recommended
extendedResponse None Set to True to get the response with additional fields or in more practical format (enables JSON response from res.php API endpoint). Suitable for ClickCaptcha, Canvas

To get the answer manually use get_result method

Solve captcha

When you submit any image-based CAPTCHA, you can provide additional options to help 2captcha workers solve it properly.

Captcha options

Option Default Value Description
numeric 0 Defines if the captcha contains numeric or other symbols see more info in the API docs
minLen 0 minimal answer length
maxLen 0 maximum answer length
phrase 0 defines if the answer contains multiple words or not
caseSensitive 0 defines if the answer is case sensitive
calc 0 defines captcha requires calculation
lang - defines the captcha language; see the list of supported languages
hintImg - an image with a hint shown to workers with the captcha
hintText - hint or task text shown to workers with the captcha

Below, you can find basic examples for every captcha type. Check out examples directory for more examples with all available options.

Normal Captcha

API method description.

To bypass a normal captcha (distorted text on an image) use the following method. This method can also be used to recognize any text in an image.

result = solver.normal('path/to/captcha.jpg', param1=..., ...)
# OR
result = solver.normal('https://site-with-captcha.com/path/to/captcha.jpg', param1=..., ...)

Audio Captcha

API method description.

Use the following method to bypass an audio captcha (mp3 formats only). You must provide the language as lang = 'en'. Supported languages are "en", "ru", "de", "el", "pt", "fr".

result = solver.audio('path/to/captcha.mp3', lang = 'lang', param1=..., ...)
# OR
result = solver.audio('https://site-with-captcha.com/path/to/captcha.mp3', lang = 'lang', param1=..., ...)

Text Captcha

API method description.

This method can be used to bypass a captcha that requires answering a question provided in clear text.

result = solver.text('If tomorrow is Saturday, what day is today?', param1=..., ...)

reCAPTCHA v2

API method description.

Use the following method to solve reCAPTCHA V2 and obtain a token to bypass the protection.

result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                          url='https://mysite.com/page/with/recaptcha',
                          param1=..., ...)

reCAPTCHA v3

API method description.

This method provides a reCAPTCHA V3 solver and returns a token.

result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                            url='https://mysite.com/page/with/recaptcha',
                            version='v3',
                            param1=..., ...)

FunCaptcha

API method description.

FunCaptcha (Arkoselabs) solving method. Returns a token.

result = solver.funcaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                            url='https://mysite.com/page/with/funcaptcha',
                            param1=..., ...)

GeeTest

API method description.

Method to solve GeeTest puzzle captcha. Returns a set of tokens as JSON.

result = solver.geetest(gt='f1ab2cdefa3456789012345b6c78d90e',
                        challenge='12345678abc90123d45678ef90123a456b',
                        url='https://www.site.com/page/',
                        param1=..., ...)

GeeTest v4

API method description.

Use this method to solve GeeTest v4. Returns the response in JSON.

result = solver.geetest_v4(captcha_id='e392e1d7fd421dc63325744d5a2b9c73',
                            url='https://www.site.com/page/',  
                            param1=..., ...)

Lemin Cropped Captcha

API method description.

Use this method to solve the Lemin captcha. Returns JSON with an answer containing the following values: answer, challenge_id.

result = solver.lemin(captcha_id='CROPPED_1abcd2f_a1234b567c890d12ef3a456bc78d901d',
                            div_id='lemin-cropped-captcha', 
                            url='https://www.site.com/page/',
                            param1=..., ...)

Yandex Smart

Use this method to solve Yandex Smart Captcha. Returns JSON with the token.

result = solver.yandex_smart(sitekey='0x1AAAAh45AAAAkg0s2VIOD34y5hy4h4h',
               url='http://mysite.com/', 
               proxy={'type': 'HTTPS', 'uri': 'login:password@IP_address:PORT'},
               userAgent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36')

Cloudflare Turnstile

API method description.

Use this method to solve Cloudflare Turnstile. Returns JSON with the token.

result = solver.turnstile(sitekey='0x1AAAAAAAAkg0s2VIOD34y5',
                            url='http://mysite.com/', 
                            data='foo',
                            pagedata='bar',
                            action='challenge',
                            useragent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36')

Amazon WAF

API method description.

Use this method to solve Amazon WAF Captcha also known as AWS WAF Captcha is a part of Intelligent threat mitigation for Amazon AWS. Returns JSON with the token.

result = solver.amazon_waf(sitekey='0x1AAAAAAAAkg0s2VIOD34y5',
                            iv='CgAHbCe2GgAAAAAj', 
                            context='9BUgmlm48F92WUoqv97a49ZuEJJ50TCk9MVr3C7WMtQ0X6flVbufM4n8mjFLmbLVAPgaQ1Jydeaja94iAS49ljb+sUNLoukWedAQZKrlY4RdbOOzvcFqmD/ZepQFS9N5w15Exr4VwnVq+HIxTsDJwRviElWCdzKDebN/mk8/eX2n7qJi5G3Riq0tdQw9+C4diFZU5E97RSeahejOAAJTDqduqW6uLw9NsjJBkDRBlRjxjn5CaMMo5pYOxYbGrM8Un1JH5DMOLeXbq1xWbC17YSEoM1cRFfTgOoc+VpCe36Ai9Kc='
                            url='https://non-existent-example.execute-api.us-east-1.amazonaws.com/latest'
                            param1=..., ...)

KeyCaptcha

API method description.

Token-based method to solve KeyCaptcha.

result = solver.keycaptcha(s_s_c_user_id=10,
    				   s_s_c_session_id='493e52c37c10c2bcdf4a00cbc9ccd1e8',
    				   s_s_c_web_server_sign='9006dc725760858e4c0715b835472f22-pz-',
    				   s_s_c_web_server_sign2='2ca3abe86d90c6142d5571db98af6714',
    				   url='https://www.keycaptcha.ru/demo-magnetic/', 
    				   param1=..., ...)

atbCAPTCHA

API method description.

Use this method to solve atbCaptcha challenge. Returns a token to bypass the captcha.

result = solver.atb_captcha(app_id='af25e409b33d722a95e56a230ff8771c',
                            api_server='https://cap.aisecurius.com',
                            url='http://mysite.com/', 
                            param1=..., ...)

Capy

API method description.

Token-based method to bypass Capy puzzle captcha.

result = solver.capy(sitekey='PUZZLE_Abc1dEFghIJKLM2no34P56q7rStu8v',
                     url='http://mysite.com/',
                     api_server='https://jp.api.capy.me/',
                     param1=..., ...)

Grid

API method description.

The grid method was originally called the Old reCAPTCHA V2 method. The method can be used to bypass any type of captcha where you can apply a grid on an image and click specific grid boxes. Returns numbers of boxes.

result = solver.grid('path/to/captcha.jpg', param1=..., ...)

Canvas

API method description.

The canvas method can be used when you need to draw a line around an object on an image. Returns a set of points' coordinates to draw a polygon.

result = solver.canvas('path/to/captcha.jpg', param1=..., ...)

ClickCaptcha

API method description.

The ClickCaptcha method returns the coordinates of points on the captcha image. It can be used if you need to click on particular points in the image.

result = solver.coordinates('path/to/captcha.jpg', param1=..., ...)

Rotate

API method description.

This method can be used to solve a captcha that asks to rotate an object. It is mostly used to bypass FunCaptcha. Returns the rotation angle.

result = solver.rotate('path/to/captcha.jpg' or 'base64', param1=..., ...)

MTCaptcha

API method description.

Use this method to solve MTCaptcha and obtain a token to bypass the protection.

result = solver.mtcaptcha(sitekey='MTPublic-KzqLY1cKH',
                          url='https://2captcha.com/demo/mtcaptcha',
                          param1=..., ...)

Friendly Captcha

API method description.

Friendly Captcha solving method. Returns a token.

result = solver.friendly_captcha(sitekey='FCMGEMUD2KTDSQ5H',
                                 url='https://friendlycaptcha.com/demo',
                                 param1=..., ...)

Cutcaptcha

API method description.

Use this method to solve Cutcaptcha. Returns the response in JSON.

result = solver.cutcaptcha(misery_key='ad52c87af17e2ec09b8d918c9f00416b1cb8c320',
                           apikey='SAs61IAI',
                           url='https://mysite.com/page/with/cutcaptcha',
                           param1=..., ...)

Tencent

API method description.

Use this method to solve Tencent captcha. Returns a token.

result = solver.tencent(app_id="197326679",
                        url="https://mysite.com/page/with/tencent",
                        param1=..., ...)

DataDome

API method description.

Use this method to solve DataDome captcha.

result = solver.datadome(captcha_url="https://geo.captcha-delivery.com/captcha/?initialCid=...",
                         pageurl="https://mysite.com/page/with/datadome",
                         userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
                         proxy={
                            'type': 'HTTP',
                            'uri': 'login:password@IP_address:PORT'
                         },
                         param1=..., ...)

VKImage

API method description.

This method can be used to solve VK captcha using graphical captcha. Returns the number of steps and solution value in the target site's API format.

result = solver.vkimage('path/to/captcha.jpg', steps='[5,4,7,7,14,22,8,...]', ...)

VKCaptcha

API method description.

This method can be used to solve VK Captcha using a token. Returns a token.

result = solver.vkcaptcha(redirect_uri='https://id.vk.ru/...',
                          userAgent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36..',
                          proxy={
                            'type': 'HTTP',
                            'uri': 'login:password@IP_address:PORT'}
                          )

CaptchaFox

API method description.

This method can be used to solve CaptchaFox using a token. Returns a token.

result = solver.captchafox(sitekey='sk_ILKWNruBBVKDOM7dZs59KHnDLEWiH',
                           pageurl='https://mysite.com/page/with/captchafox',
                           userAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
                           proxy={'type': 'HTTPS',
                                  'uri': 'login:password@IP_address:PORT'})

Prosopo

API method description.

This method can be used to solve Prosopo captcha using a token. Returns a token.

result = solver.prosopo(sitekey='5EZVvsHMrKCFKp5NYNoTyDjTjetoVo1Z4UNNb1DkVLS0JbqR',
                        pageurl='https://mysite.com/page/with/prosopo'
                        )

Temu

API method description.

This method can be used to solve Temu captcha. Returns a coordinates.

result = solver.temu(body="data:image/png;base64,iVBORw0KG...",
                     part1="data:image/png;base64,iVBORw0KG...",
                     part2="data:image/png;base64,iVBORw0KG...",
                     part3="data:image/png;base64,iVBORw0KG...")

CyberSiARA

API method description.

Use this method to solve CyberSiARA. Returns a token.

result = solver.cybersiara(master_url_id='tpjOCKjjpdzv3d8Ub2E9COEWKt1vl1Mv',
                           pageurl='https://demo.mycybersiara.com/',
                           userAgent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
                           param1=..., ...)

Altcha Captcha

API method description.

Use this method to solve Altcha Captcha. Returns a token.

result = solver.altcha(pageurl='https://mysite.com/page/with/altcha',
                       challenge_json='{"algorithm":"SHA-256","challenge":"a4c9d8e7f1b23a6c...",..."signature":"7b3e2a9d5c8f1046e2d91c3a..."}',
                       # challenge_url='https://example.com/altcha-challenge',)

Binance

API method description.

Use this method to solve Binance Captcha. Returns a token.

result = solver.binance(sitekey='register',
                        pageurl='https://mysite.com/page/with/binance',
                        validate_id='e20c622fa9384952832fc1c2a6b75c0a',)

Yidun

API method description.

Use this method to solve Yidun - NECaptcha. Returns a token.

result = solver.yidun(sitekey='6b4d7e0c4f5a4c7db2f3a1e8c9d6f123',
                      pageurl='https://mysite.com/page/with/yadun',
    )

Hunt

API method description.

Use this method to solve Hunt captcha. Returns a token.

result = solver.hunt(pageurl='https://example.com/page-with-hunt',
                     api_get_lib='https://example.com/hd-api/external/apps/app-id/api.js',
                     )

Alibaba

API method description.

Use this method to solve Alibaba captcha. Returns a token.

result = solver.alibaba(pageurl='https://www.example.com',
                        scene_id='abc123xyz4',
                        prefix='dlw3kug',
                        )

TSPD

API method description.

Use this method to solve TSPD captcha. Returns a JSON string with cookies.

result = solver.tspd(pageurl='https://example.com/login',
                     tspd_cookie='TS386a400d029=082670...010245; TS386a400d078=082670...dbb3b0c',
                     html_page_base64='PCFET0NUWVBFIGh0bWw+...',
                     proxy={'type': 'HTTP', 'uri': 'login:password@IP_address:PORT'},
                     )

Basilisk

API method description.

Use this method to solve Basilisk captcha. Returns a token.

result = solver.basilisk(pageurl='https://example.com/login',
                         sitekey='b7890h...19fb2600897',
                         )

Drag & Drop

API method description.

Use this method to solve a captcha where one or more images need to be dragged onto specific positions on a background image. body and each item in images can be a file path, a URL, or a Base64-encoded string.

Returns the standard result dictionary {'captchaId': 'TASK_ID', 'code': 'COORDINATES'}. The coordinates string in result['code'] contains one entry per image from images, in the same order, separated by |. An image that wasn't moved may be returned by the API as null.

result = solver.drag_and_drop(
    body='path/to/background.jpg',
    images=['path/to/image1.jpg', 'path/to/image2.jpg'],
)

coordinates = result['code']

Imperva (Incapsula)

API method description.

Use this method to solve Imperva (Incapsula) captcha. Returns a JSON string with cookies.

result = solver.imperva(pageurl='https://example.com/login',
                        incapsula_script_url='/_Incapsula_Resource?SWUDNSAI=31&xinfo=1',
                        incapsula_cookies='visid_incap_123456=sample; incap_ses_123_123456=sample',
                        proxy={'type': 'HTTP', 'uri': 'login:password@IP_address:PORT'},
                        )

The cookies from domains must be passed to the target website. If the solution contains headers.User-Agent, use the same User-Agent for requests to the website.

Other methods

send / get_result

These methods can be used for manual captcha submission and answer polling. The send() method supports sending any captcha type, to specify the captcha type you must send value method manually, for example method='recaptcha' for solving reCaptcha. You can find the value of the method parameter in the API documentation.

Example for solving Normal captcha manually:

import time
. . . . . 


id = solver.send(file='path/to/captcha.jpg')
time.sleep(20)

code = solver.get_result(id)

balance

API method description.

Use this method to get your account's balance

balance = solver.balance()

report

API method description.

Use this method to report good or bad captcha answers.

solver.report(id, True) # captcha solved correctly
solver.report(id, False) # captcha solved incorrectly

Error handling

In case of an error, the captcha solver throws an exception. It's important to properly handle these cases. We recommend using try except to handle exceptions. The list of all errors can be found in the API documentation.

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)

Proxies

You can pass your proxy as an additional argument for the following methods: recaptcha, funcaptcha, geetest, geetest v4, keycaptcha, capy puzzle, lemin, atbcaptcha, turnstile, amazon waf, mtcaptcha, friendly captcha, cutcaptcha, Tencent, DataDome, cybersiara, Yandex Smart, VKCaptcha, CaptchaFox, Prosopo, Altcha, Binance, Yidun, Hunt, Alibaba, TSPD, Basilisk, Imperva (Incapsula).

The proxy will be forwarded to the API to solve the captcha.

We have our own proxies that we can offer you. Buy residential proxies to avoid restrictions and blocks. Quick start.

proxy={
    'type': 'HTTPS',
    'uri': 'login:password@IP_address:PORT'
}

Async calls

To use the async version, just replace TwoCaptcha with AsyncTwoCaptcha:

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())

The AsyncTwoCaptcha class supports all the same methods and parameters as the synchronous TwoCaptcha class but operates asynchronously. Configuration is identical.

Solving Multiple Captchas in Parallel

One of the main advantages of using async support is the ability to solve multiple captchas concurrently:

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())

Examples of solving all supported captcha types asynchronously are located in the examples/async directory directory.

Legacy Async Method

For backward compatibility, you can also use the traditional executor-based approach with the synchronous client:

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))

Examples

Examples of solving all supported captcha types are located in the examples directory.

Examples using Selenium

Also we have a separate repository you can find examples of captcha solving using Selenium library. At the moment we have implemented examples of bypassing reCAPTCHA, Cloudflare, Coordinates, MTCaptcha, normal captcha (image captcha) and text captcha using Selenium.

Useful articles

Get in touch

Join the team 👪

There are many ways to contribute, of which development is only one! Find your next job. Open positions: AI experts, scrapers, developers, technical support, and much more! 😍

License

The code in this repository is licensed under the MIT License. See the LICENSE file for more details.

Graphics and Trademarks

The graphics and trademarks included in this repository are not covered by the MIT License. Please contact support for permissions regarding the use of these materials.

Metadata

Release files for 2captcha-python 2.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for 2captcha-python 2.1.2
File Size Uploaded Provenance Actions
2captcha_python-2.1.2.tar.gz 51.2 kB Without provenance Details for 2captcha_python-2.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for 2captcha-python 2.1.2
File Interpreter ABI Platform Actions
2captcha_python-2.1.2-py3-none-any.whl Python 3 none any Details for 2captcha_python-2.1.2-py3-none-any.whl

Total release size: 87.4 kB

Release files / 2captcha_python-2.1.2.tar.gz

Download URL 2captcha_python-2.1.2.tar.gz
Size 51.2 kB
Tags Source
SHA-256 checksum
How to use checksums
ba3dbf34fd95247ea5ad8ff4f3f9475f55314ac6a9d3748cbcfdfc9a95df0d37
BLAKE2b-256 checksum
How to use checksums
597ab66cf008235da24b298038517591cb34b892652b63db9b51e52aadb33e89
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / 2captcha_python-2.1.2-py3-none-any.whl

Download URL 2captcha_python-2.1.2-py3-none-any.whl
Size 36.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
de16159921c5b34c39be151ae3a23c47ee24df43933b38b571f801c5ea896304
BLAKE2b-256 checksum
How to use checksums
29fef9e662ee35e0ee04fc5e217ab026310504cfcffdc7335d2089581853c316
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for 2captcha-python 2.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.1.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page