MTCaptcha in Python: Scrape the Sitekey, Solve and Post

mtcaptcha in python - MTCaptcha in Python: Scrape the Sitekey, Solve and Post

To handle MTCaptcha in Python without a browser, load the login page with requests, read the sitekey and the action out of its mtcaptchaConfig object, pass both to solver.mtcaptcha() from the CapSkip SDK, and send the token it returns in the mtcaptcha-verifiedtoken field of the form submission. Behind the call sits the CapSkip MTCaptcha solver, which runs on your own Windows PC under a flat license, so a token that gets refused costs you nothing but another pass through the loop.

What you need

  • A Windows PC with CapSkip 4.3.0 (9 November 2026, the first release with MTCaptcha) or later. The setup guide covers installing it. The copy on my PC accepted the mt_captcha method, but I couldn’t read its version.
  • Python 3.10 or newer, the floor declared by capskip 1.7.0, requests 2.34.2 and urllib3 2.8.0, plus capskip 1.7.0 or newer, the first version with an MTCaptcha method. I ran them on Python 3.11.7, 3.13.7 and 3.14.0 only.
  • Both packages install from PowerShell with python -m pip install capskip requests (py -m pip works too), so pip need not be on your PATH.
  • An address for CapSkip. In Local mode (127.0.0.1) only the PC running CapSkip can reach it. Server mode adds your network or public IP, which lets another PC or a Windows VPS send the same requests. Both modes are described under connection settings in the setup guide. Leave any Service Emulator setting on its default, because the SDK talks to CapSkip in its default format and an emulated service may answer differently.

I tested this script against two mocks I wrote, one playing CapSkip and one playing a login site. The real CapSkip app on my PC took three MTCaptcha tasks, with the public demo sitekey and page address from the SDK’s own example, to see a real token and time the SDK call. No site ever checked a token, so nothing here shows that a real site accepts one, and every site rule in the mock is mine. For how a site checks a token, see the MTCaptcha token validation guide.

Step 1: set up the session and find the MTCaptcha sitekey

Save the first code block as mtcaptcha_login.py. Every block after it, including the next one in this step, goes at the end of the same file in the order shown, and the file is complete after Step 4. One User-Agent string serves the page load, the solve and the form submission, so pick any current browser string. In Server mode, put your server’s address in host. With API Key Validation on, also pass your key as apiKey.

# python -m pip install capskip requests
import re

import requests
from capskip import ApiException, CapSkip

LOGIN_URL = "https://example.com/login"  # the page that shows the widget
USER_AGENT = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
    "(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
)

# Local mode. In Server mode, use your server's address as the host.
solver = CapSkip(host="127.0.0.1", port=8080)

Most MTCaptcha pages configure the widget with an inline mtcaptchaConfig object whose sitekey value starts with MTPublic-, and it may also set an action. The CapSkip demo page writes it on one line with a lang key, three callbacks and no action. The CapSkip docs spread it over lines and add an action. Other pages use single quotes and bare keys. The function below looks for each key by name, so it reads all of these, but an inline function inside the object, or a script that does not end the object with a closing brace and semicolon or with the closing script tag, would defeat it.

It raises an error when the page has no such object or no sitekey in it, and the first is a real case. A GET of 2Captcha’s demo page returned HTML in which the sitekey appears only in its instructions. For a page like that, copy the sitekey once from the widget’s iframe address, where it is the sitekey query parameter on service.mtcaptcha.com. If the page sets an action, send it: MTCaptcha’s action documentation says the check call reports the action the widget started with, so a site can compare it. If it sets none, send none.

def read_config(html):
    """Return (sitekey, action) from the page's mtcaptchaConfig object."""
    found = re.search(r"mtcaptchaConfig\s*=\s*\{(.*?)(?:\}\s*;|</script>)", html, re.S)
    if not found:
        raise RuntimeError("no mtcaptchaConfig in the page source")

    def value(name):
        pattern = r"(?<![\w-])[\"']?" + name + r"[\"']?\s*:\s*[\"']([^\"']+)[\"']"
        pair = re.search(pattern, found.group(1))
        return pair.group(1) if pair else None

    sitekey = value("sitekey")
    if not sitekey:
        raise RuntimeError("no sitekey in mtcaptchaConfig")
    return sitekey, value("action")

I ran read_config on the three quoting styles from my mock, on a nested object before the sitekey and before the action, on a config with no trailing semicolon, and on saved copies of two public pages. The CapSkip demo page gave its sitekey and no action, and 2Captcha’s demo page raised the error above. All three Python versions agreed.

Step 2: request the token through the SDK

You call solver.mtcaptcha(sitekey, url, **options). It submits the task, polls for the result and returns a dictionary, so you write no loop. Pass the page’s real address as url, because MTCaptcha only issues tokens for the domains a sitekey is registered for. Add this function to the end of the file. It adds the action only when the page set one.

def get_token(sitekey, action):
    options = {"userAgent": USER_AGENT}
    if action:  # only when the page's config sets one
        options["action"] = action
    return solver.mtcaptcha(sitekey, LOGIN_URL, **options)["token"]

Before anything is sent, the SDK validates your arguments. A sitekey that is not MTPublic- followed by up to 55 letters, digits, hyphens or underscores, a page address that is not an absolute http or https URL, or an option the MTCaptcha API does not take, such as invisible, raises ValidationException at once. A sitekey pasted as sk=MTPublic- is accepted, and the SDK strips the prefix.

In three real runs the dictionary held the keys "captchaId", "code" and "token", and the last two are the same string, the one for mtcaptcha-verifiedtoken. Every real token began with v1( and ended with **), was 418 characters long and had five comma separated fields, the third of them the sitekey. The docs print shorter samples, so don’t validate a token by its length.

The userAgent option names the browser string that CapSkip presents to MTCaptcha. I pass the session’s own string, so the solve, the page load and the form submission show one browser. Without it, CapSkip uses a Chrome for Windows string. Nothing I read says MTCaptcha compares the two, and I did not test that. The live API docs list ERROR_WRONG_USERAGENT for a User-Agent that cannot be used for the task, and the real app never saw my userAgent option, so if it answers that error, leave the option out of get_token.

Timing, from just before the call to its return: 3.77 seconds once on Python 3.14.0 and 3.76 seconds twice on 3.11.7, with capskip 1.7.0, default polling and the real CapSkip app on Windows 11. Those three calls sent neither userAgent nor action. The SDK’s polling schedule shapes that figure: against the mock it asked for the result at 0, 0.25, 0.76, 1.76, 3.76 and 7.76 seconds after the submit, and a mock token ready anywhere from 1.9 to 3.6 seconds came back at 3.76. So the real solve finished between the 1.76 and 3.76 second polls, and three runs are not a benchmark.

No browser runs for an MTCaptcha solve, so the SDK waits as long as its defaultTimeout allows, 120 seconds by default. With defaultTimeout lowered to 6 seconds, a mock that never answered raised TimeoutException 7.78 seconds after the call, because the last sleep between polls ran past the limit.

Step 3: submit the form while the token is fresh

In a browser the widget writes the token into a hidden input named mtcaptcha-verifiedtoken. Without a browser, you send that field yourself, next to the form’s own fields. The function below, also added to the end of the file, does that. The session carries the page’s cookies into the form post. If the form’s action points elsewhere, change the first argument of the session.post call.

A token works once, and only for a short time. MTCaptcha’s validation guide says a token is normally valid for a few minutes but gives a default expiry of 60 to 120 seconds, and by default it can be checked only once, so send it within a minute. CapSkip’s docs ask you to request the token just before the form post, so get_token runs after the page load and the form post follows at once. If you add a wait of your own, solve after it. A refused token is spent, so the Step 4 loop asks for a new one.

The form post also names the page as Referer, because requests sends neither Referer nor Origin, and some frameworks refuse an HTTPS form post with neither. My mock plays one, and without the header it answered 403.

def post_form(session, token, username, password):
    return session.post(
        LOGIN_URL,
        data={
            "username": username,  # your form's own fields go here
            "password": password,
            "mtcaptcha-verifiedtoken": token,
        },
        headers={"Referer": LOGIN_URL},  # requests sends none by itself
        timeout=30,
    )

Step 4: the full login script for MTCaptcha in Python

Add the last block to the end of mtcaptcha_login.py, which is then complete. Set LOGIN_URL and run python mtcaptcha_login.py (or py mtcaptcha_login.py). Two strings are placeholders for your site: "Welcome", the text a successful login shows, and "captcha check failed", a phrase that your site’s own captcha refusal contains. It gives up after three attempts.

According to the CapSkip docs, ERROR_CAPTCHA_UNSOLVABLE is answered by submitting a new task, and the script retries that code alone. The docs name two failures that repeat if you resubmit the same task, an unknown sitekey and a sitekey not allowed on the page’s domain, and every other error stops the script too. Inside the ApiException message the code arrives as bare text or wrapped in a JSON envelope, and which_error pulls it out of either.

A refused form post gets a new token only if the reply contains your site’s captcha refusal phrase. Use a phrase like the quoted one, never the bare word captcha. A login page shown again after a wrong password still carries the widget’s own mtcaptchaConfig and mtcaptcha-verifiedtoken, so the bare word would match and spend three tokens. I saw that against my mock. With a phrase only the refusal contains, one task is spent.

def which_error(err):
    # The message holds the code as bare text or inside a JSON envelope.
    found = re.search(r"ERROR_[A-Z_]+", str(err))
    return found.group(0) if found else str(err)


def log_in(username, password):
    session = requests.Session()
    session.headers["User-Agent"] = USER_AGENT
    for attempt in range(1, 4):
        page = session.get(LOGIN_URL, timeout=30)  # cookies first, then config
        sitekey, action = read_config(page.text)
        try:
            token = get_token(sitekey, action)
        except ApiException as err:
            code = which_error(err)
            if code != "ERROR_CAPTCHA_UNSOLVABLE":
                raise  # a bad sitekey or domain would fail the same way again
            print(f"attempt {attempt}: {code}, new task")
            continue
        reply = post_form(session, token, username, password)
        if "Welcome" in reply.text:  # use a sign your site shows on success
            return reply
        if "captcha check failed" not in reply.text.lower():  # your site's phrase
            raise RuntimeError(f"login refused ({reply.status_code}), not the captcha")
        print(f"attempt {attempt}: captcha refused ({reply.status_code}), new token")
    raise RuntimeError("no login after 3 attempts")


if __name__ == "__main__":
    print(log_in("alice", "YOUR_PASSWORD").text[:40])

Against the mock, all three Python versions gave identical results:

Mock settingWhat the script did
Page config as in the docs, with an actionOne task, in.php received the action, the form post was accepted
Config on one line with callbacks and no action, like the demo pageOne task, no action field sent, the form post was accepted
Page sets an action but the call leaves it outThree tasks, three refused form posts, then RuntimeError
First two solves end in ERROR_CAPTCHA_UNSOLVABLETwo retry messages, then the third task’s token was accepted
Token 3 seconds old when sent, mock lifetime set to 2 secondsRefused as stale, then a new token was accepted
Unknown sitekey or domain error on the pollApiException after one task and no form post, as JSON or as bare text
Wrong password with a plain refusal text, or a form post without the Referer headerRuntimeError after one task, no new token
Login page shown again after a wrong password, tested for the bare word captchaThree tasks, then RuntimeError. With the phrase test, one task

Read the table as a test of my mock, not of any real site. Single use, a short lifetime and the action match follow the docs, but the two second lifetime is an arbitrary number of mine.

Common errors

Most of these errors come from the CapSkip MTCaptcha API docs, except where a row says that I saw it myself.

ErrorCauseFix
ValidationExceptionThe SDK refused the call before sending it, for one of the reasons in Step 2The message names the problem, so fix that argument
ERROR_RECAPTCHA_INVALID_SITEKEYMTCaptcha does not recognise the sitekeyCopy it again from mtcaptchaConfig. A resend would fail, so the script raises
ERROR_RECAPTCHA_INVALID_DOMAINThe sitekey is not allowed on the domain of the address you sentUse the address of the page the widget really sits on
ERROR_CAPTCHA_UNSOLVABLEMTCaptcha was not passedSubmit a new task, which the script does for you up to three times
ERROR_TASK_NOT_SUPPORTEDCapSkip is older than the release that added MTCaptchaInstall CapSkip 4.3.0 or a later release
ERROR_WRONG_USERAGENTThe live API docs list it for a User-Agent that cannot be used for the task. The real app never saw the userAgent option from my codeLeave the userAgent option out of get_token
ERROR_WRONG_USER_KEY or ERROR_KEY_DOES_NOT_EXISTAPI Key Validation is on and the key is wrong. A call without apiKey goes out with the key capskipGive CapSkip() your real key as its apiKey
TimeoutExceptionNo token within defaultTimeout, 120 seconds unless you changed itWatch the task in CapSkip’s Monitor, then run the script again
NetworkExceptionNothing is answering on that host and port when the task is sent, or the reply was an HTTP error. If CapSkip stops answering during the poll, you get TimeoutException insteadLaunch CapSkip and confirm that the host and port match its connection settings
A site refuses a token that seems fineThe token was used before, was too old, left out the page’s action, or came with no RefererSend each token once, right away, with the page as Referer and the page’s own action

FAQ

Can the script run on a different machine from CapSkip?

Yes, through Server mode. Switch it on in the connection settings of the CapSkip PC and pass that PC’s address as host to CapSkip(). Nothing else changes. Server mode requires administrator rights for CapSkip, and the setup guide recommends a static public IP. When Server mode starts, CapSkip opens its port to every address, so add a Windows Firewall block rule for the machines that should not reach it. The solver stays on your own Windows hardware and nothing is metered.

Does the script work with invisible MTCaptcha widgets?

CapSkip’s MTCaptcha solver page says an invisible widget goes through the same request as the visible one and returns the same kind of token. The MTCaptcha section of the API docs does not mention invisible mode, and I ran nothing against an invisible widget, so treat it as unconfirmed. Your page still has to carry the sitekey in its source, because read_config needs it there.

Do I need a proxy for MTCaptcha?

Not to start. The docs call one address fine for testing, but say that constant solving from a single address invites rate limiting. For volume, load a proxy list in the MTCaptcha settings of the app, or pass a proxy option to mtcaptcha(), such as proxy={"type": "HTTP", "uri": "login:password@IP:PORT"}. The mock received the proxy and its type; I used no real proxy.

The short version

MTCaptcha in Python comes down to three moves: read the sitekey and action from the page, ask for a token just before the form post, and ask again when a form post is refused. Because CapSkip is a local captcha solver that you run yourself, a refused token never adds to a bill. The Python CAPTCHA solver page lists the SDK calls for other types, and the MTCaptcha demo lets you try a token in a real form.