AWS WAF and other CAPTCHAs
How to solve MTCaptcha in Python
MTCaptcha hands the form a verified token in a hidden field, and that token is all your script needs to supply. This guide gets it with nothing but the Python standard library, at $2.10 per 1,000.
How MTCaptcha fits into a form
MTCaptcha is a text CAPTCHA widget that sites embed in their own pages. A visitor types the distorted characters, the widget checks them with MTCaptcha's servers, and on success it writes a verified token into a hidden input named mtcaptcha-verifiedtoken. The form posts that token, and the site's back end confirms it with MTCaptcha before accepting the submission.
So the job for your script is the same as with any token CAPTCHA: get a valid token for the right site key and page, then post it under the right field name. The MTCaptcha glossary entry has more about the widget itself.
Why the standard library
Many automation hosts are locked down: a CI runner without network access to package indexes, a hardened server, or a one file utility you want colleagues to run without installing anything. Python's urllib.request, http.cookiejar and json are enough for this flow. If your project already uses an HTTP library, the logic carries over line for line.
Find the site key
MTCaptcha site keys start with MTPublic-. They appear in the page's configuration script, typically an object called mtcaptchaConfig with a sitekey property, which the widget loader reads. One pattern search covers the usual quoting styles.
import re
KEY_PATTERN = re.compile(r"MTPublic-[A-Za-z0-9]+")
def mt_site_key(html: str) -> str:
match = KEY_PATTERN.search(html)
if match is None:
raise LookupError("no MTPublic- key in this page")
return match.group(0)
If the page builds its configuration in a separate JavaScript file, search that file instead, or open DevTools and type mtcaptchaConfig.sitekey in the Console.
A cookie aware opener
Forms often set a session cookie on the first visit and expect it back with the submit. An opener built with HTTPCookieProcessor keeps those cookies for you, the same way a browser would.
import http.cookiejar
import urllib.request
jar = http.cookiejar.CookieJar()
site = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
site.addheaders = [("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) form-qa/0.9")]
def page_text(url: str) -> str:
with site.open(url, timeout=20) as resp:
return resp.read().decode(resp.headers.get_content_charset() or "utf-8")
Create the task and poll
The task type is MtCaptchaTaskProxyLess with websiteURL and websiteKey. The solution carries a single token string that starts with v1(. The API calls go through a plain urlopen, not the cookie opener, so the target site's cookies never travel to the API.
import json
import time
from urllib.request import Request, urlopen
MT_API = "https://gatesolver.com"
MT_CLIENT = "YOUR_API_KEY"
def mt_post(method: str, body: dict) -> dict:
body = dict(body, clientKey=MT_CLIENT)
req = Request(f"{MT_API}/{method}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", "Accept": "application/json"}, method="POST")
with urlopen(req, timeout=30) as resp:
answer = json.load(resp)
if answer.get("errorId"):
raise RuntimeError(f"{answer.get('errorCode')}: {answer.get('errorDescription', '')}")
return answer
def mt_token(page_url: str, site_key: str) -> str:
ticket = mt_post("createTask", {"task": {
"type": "MtCaptchaTaskProxyLess",
"websiteURL": page_url, "websiteKey": site_key}})["taskId"]
for _ in range(40):
time.sleep(3)
reply = mt_post("getTaskResult", {"taskId": ticket})
if reply["status"] == "ready":
return reply["solution"]["token"]
if reply["status"] == "failed":
raise RuntimeError(f"MTCaptcha task {ticket} failed (free)")
raise TimeoutError(f"MTCaptcha task {ticket} is still processing")
An error such as ERROR_CAPTCHA_UNSOLVABLE raises immediately and costs nothing. The loop gives up after about two minutes, the point at which an unsolved task is marked failed and stays free.
Send the form with the verified token
Read the form once in DevTools to list its fields, then send them together with mtcaptcha-verifiedtoken. The helper below encodes the fields as a normal form post through the cookie aware opener.
import urllib.parse
form_url = "https://example.com/newsletter/join"
html = page_text(form_url)
token = mt_token(form_url, mt_site_key(html))
fields = {"email": "qa-list@example.com", "mtcaptcha-verifiedtoken": token}
with site.open(form_url, data=urllib.parse.urlencode(fields).encode(), timeout=20) as done:
print(done.status, done.geturl())
Passing data to open() turns the request into a POST with the application/x-www-form-urlencoded content type. If the site posts JSON through JavaScript instead, capture that request in the Network panel and build the same JSON body with the token in the field the page uses.
Token lifetime
A verified token is meant for one submission and is only valid for a short time after it is issued, so solve right before you post. Do not store tokens for later, and do not post one token twice: the second use fails even if the first one never reached the back end. If your script fills several fields or waits for other data, move the solve to the end, directly before the submit.
Check the result like a test
For form QA you want a clear pass or fail. Read the response after the post and assert something concrete: a redirect to a thank you page, a success message in the HTML, or a JSON status. A 200 status alone tells you little, because many forms re-render the same page with an error message and status 200.
- Compare
done.geturl()with the expected landing URL after redirects. - Search the response text for the site's own success message.
- When the site reports "invalid captcha", log the task id and the time between solve and submit.
Running it in a CI pipeline
Because the script has no dependencies, it drops straight into a CI job as a smoke test for a staging form. Read the API key from a masked pipeline variable with os.environ instead of the constant shown above, and make the script exit with a non zero status when the success check fails, so the pipeline turns red on a broken form. Run it after each deploy rather than on every commit: one solved task per deploy costs a fraction of a cent and still catches the usual regressions, such as a renamed field, a missing widget script or a back end that stopped verifying tokens. If your staging site uses its own MTCaptcha site key, keep that key in the pipeline configuration too, so the test never touches the production widget.
Errors and fixes
| What you see | What to change |
|---|---|
| LookupError from mt_site_key | The key is set in an external script; search that file or the Console. |
| ERROR_INVALID_TASK_DATA | The description names the field; check websiteKey starts with MTPublic-. |
| ERROR_KEY_DENIED_ACCESS | The API key was regenerated or mistyped; copy the current one from the account. |
| Site rejects the token | Submit sooner, use the exact page URL, and never reuse a token. |
The MTCaptcha solver page lists the current price, and the API docs describe every error code in detail.
Common questions
How can I recognise an MTCaptcha site key?
It starts with MTPublic- followed by letters and digits, and it is usually set as sitekey in the page's mtcaptchaConfig object.
Which field receives the token?
The hidden input named mtcaptcha-verifiedtoken. Post the token under that name with the rest of the form fields.
Does this need the requests package?
No. The example uses urllib.request, http.cookiejar and json from the standard library, so it runs on any Python 3.9 or newer.
Can one MTCaptcha token be used for two submissions?
No. Each token is for one submission and expires quickly, so solve directly before every post.
Does MTCaptcha need a proxy task?
The proxyless MtCaptchaTaskProxyLess type is the one offered for MTCaptcha, and it covers ordinary form pages.
Keep reading
- MTCaptcha solver$2.10 per 1,000 tasks, answers under 5 seconds.
- MTCaptchaThe MTCaptcha text-image widget, its MTPublic site key, and the verified token field that forms submit.
- CAPTCHA tokenThe signed string a widget returns after a pass, how long it lives, and how site servers check it.
- Can one CAPTCHA token be used twice?Token answers are single use by design; the vendor marks them spent at the first server check, so reuse fails.