Python captcha solver: a complete API client

A Python captcha solver is a short script that sends a CAPTCHA challenge to a solver API and reads the answer back. With ilovecaptcha it takes two HTTPS calls, createTask then getTaskResult, written with the standard library alone: urllib.request, json, base64 and time. This page explains each step and gives the complete file.

Updated on · Written and maintained by the ilovecaptcha team

Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.

How do you call a captcha solver API from Python?

With urllib.request and json, both in the standard library. The example builds one helper, post, which adds the API key to the body under clientKey, serialises it with json.dumps, sends it as application/json and decodes the reply with json.load. Every call of the API goes through that helper, so the script needs neither requests nor any other package.

The Python example at a glance
Item Value
Runs on Python 3.8 or newer
Packages to install None: standard library only
File solve.py
Command python solve.py
HTTP client urllib.request

How do you send the captcha image and wait for the answer in Python?

Read the image as bytes, encode it with base64.b64encode and decode the result to a string, since JSON carries text only. solve posts the task to createTask, keeps the taskId, then calls getTaskResult after each time.sleep until status is ready.

  • POLL_SECONDS is 1.5: one request every second and a half.
  • TIMEOUT_SECONDS is 120: past that, solve raises TimeoutError.
  • The deadline uses time.monotonic, which a clock change cannot shift.
  • A reply already marked ready by createTask is returned at once.

How do you handle the API key and errors in Python?

Keep the key out of the file. The example holds it in the constant API_KEY; in a real project, read it with os.environ from a variable such as ILOVECAPTCHA_KEY, so that it never reaches a repository. Errors come back as JSON: when errorId is not 0, post raises RuntimeError with errorCode and errorDescription. A network failure raises urllib.error.URLError, to catch around solve.

What does a complete Python captcha solver client look like?

The file below is the whole client, in 44 lines. It defines post, solve and get_balance, then reads captcha.png from the current folder, submits it as an aws-waf task and prints the solution. Replace YOUR_API_KEY and YOUR_API_URL with your own values, change the task type and its fields to match your captcha, and run it.

solve.py · Complete Python client: one createTask call, then getTaskResult until the task is ready (preview format).
import base64
import json
import time
import urllib.request

API_KEY = "YOUR_API_KEY"
BASE_URL = "YOUR_API_URL"
POLL_SECONDS = 1.5
TIMEOUT_SECONDS = 120


def post(route, body):
    payload = json.dumps({"clientKey": API_KEY, **body}).encode()
    request = urllib.request.Request(BASE_URL + route, payload, {"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
    if result.get("errorId", 0) != 0:
        raise RuntimeError(f"{result.get('errorCode')}: {result.get('errorDescription')}")
    return result


def solve(task):
    result = post("/createTask", {"task": task})
    if result.get("status") == "ready":
        return result["solution"]
    task_id = result["taskId"]
    deadline = time.monotonic() + TIMEOUT_SECONDS
    while time.monotonic() < deadline:
        time.sleep(POLL_SECONDS)
        result = post("/getTaskResult", {"taskId": task_id})
        if result.get("status") == "ready":
            return result["solution"]
    raise TimeoutError(f"task {task_id} not ready after {TIMEOUT_SECONDS} s")


def get_balance():
    return post("/getBalance", {})["balance"]


if __name__ == "__main__":
    with open("captcha.png", "rb") as f:
        image = base64.b64encode(f.read()).decode()
    print(solve({"type": "aws-waf", "image": image}))
    print(get_balance())

Python captcha solver: frequently asked questions

Do I need a pip package or an SDK to solve captchas in Python?

No. The API is plain HTTPS with a JSON body, and Python ships everything needed to call it: urllib.request for the request, json for the body and the reply, base64 for the image, time for the wait between two polls. The file on this page is the complete client. Copy it into your project and import solve from it: there is nothing to install and no version to pin.

Can I use requests, httpx or aiohttp instead of urllib?

Yes. Only the post helper changes: it must send a POST request with a JSON body that contains clientKey and return the decoded reply. With requests, that is one call to requests.post with the json argument. In asynchronous code, write post and solve as coroutines and replace time.sleep with asyncio.sleep, so that the wait between two polls does not block the event loop.

What does solve return in Python, and how do you read it?

A dictionary: the solution object of the API, already decoded by json.load. Its keys depend on the captcha. A token task returns token, a value to inject; an image task returns points, a list of x and y pairs in pixels of the image you sent; a slider returns offset, a distance in pixels; a text task returns text. Read the key that your task type returns, for instance points for an AWS WAF grid.

Sources

The facts and figures quoted on this page come from these sources.