AWS WAF and other CAPTCHAs
How to solve image text CAPTCHAs in Python
Classic text CAPTCHAs are still everywhere on older forms and internal tools. Python can read them through the API in about a second per image, at $0.28 per 1,000.
The moving parts
A text image CAPTCHA is a picture of a few distorted characters. The server remembers which characters it drew for your session, so the answer only counts when it comes back on the same session that loaded the image. The flow is therefore: load the form, download the image with the same cookies, encode it, send an ImageToTextTask, and post the returned text with the form.
This differs from token CAPTCHAs in two practical ways. The answer is ready much sooner, so you poll every second instead of every three, and the answer is the text itself, so you must respect upper and lower case exactly.
Download the image in the right session
The most common mistake is fetching the image with a fresh client. The server then draws a new picture for a new session, and the text you get back is correct for an image your form never sees. Use one requests.Session for the page, the image and the submit.
import base64
from urllib.parse import urljoin
import requests
import bs4
def image_for_form(sess: requests.Session, form_url: str, img_css: str) -> tuple[str, bs4.BeautifulSoup]:
soup = bs4.BeautifulSoup(sess.get(form_url, timeout=20).text, "html.parser")
img = soup.select_one(img_css)
if img is None:
raise LookupError(f"no element matches {img_css}")
src = img["src"]
if src.startswith("data:image"):
return src.split(",", 1)[1], soup
raw = sess.get(urljoin(form_url, src), timeout=20,
headers={"Referer": form_url}).content
return base64.b64encode(raw).decode("ascii"), soup
Some pages embed the image as a data: URI. In that case the base64 text is already in the page; the function strips the data:image/png;base64, prefix because the task wants the raw base64 only. Install the parser with pip install requests beautifulsoup4.
Send the task
The required field is body, holding the base64 image. Two optional fields help with harder images:
- module picks a recognition model for a style of text.
commonfits most images; leave it out unless you know a site needs something else. - score sets a confidence threshold between 0.8 and 1. A higher value asks for an answer only when the model is very sure, which can mean more unsolvable results but fewer wrong ones.
import time
OCR_BASE = "https://gatesolver.com"
class ImageTaskError(Exception):
pass
def read_captcha_text(b64_image: str, key: str, module: str | None = None,
score: float | None = None) -> str:
job = {"type": "ImageToTextTask", "body": b64_image}
if module:
job["module"] = module
if score is not None:
job["score"] = score
r = requests.post(f"{OCR_BASE}/createTask", timeout=30,
json={"clientKey": key, "task": job}).json()
if r.get("errorId"):
raise ImageTaskError(r.get("errorCode"))
for _ in range(60):
time.sleep(1)
p = requests.post(f"{OCR_BASE}/getTaskResult", timeout=30,
json={"clientKey": key, "taskId": r["taskId"]}).json()
if p.get("errorId") or p.get("status") == "failed":
raise ImageTaskError(p.get("errorCode", "failed"))
if p["status"] == "ready":
return p["solution"]["text"]
raise ImageTaskError("image task still processing after a minute")
A one second poll is the right rhythm for image tasks: they usually finish within a few seconds, and polling once a second keeps you far below the 600 requests per minute limit even with a few images in flight.
Submit the answer
Collect the other form fields from the parsed page, including hidden ones, add the answer under the input's own name, and post through the same session.
with requests.Session() as form_session:
url = "https://example.com/legacy/lookup"
b64, soup = image_for_form(form_session, url, "img#captcha-image")
answer = read_captcha_text(b64, "YOUR_API_KEY")
payload = {i["name"]: i.get("value", "") for i in soup.select("form input[name]")}
payload.update({"captcha_code": answer, "query": "ACME-1042"})
result = form_session.post(url, data=payload, timeout=20)
print(result.status_code, "wrong code" in result.text.lower())
Replace captcha_code with the real name of the text input. The dictionary comprehension copies hidden inputs such as CSRF tokens, which many old forms check alongside the CAPTCHA.
Case, spaces and lookalike characters
Enter the text exactly as returned. If a site is case sensitive, changing gS7k to GS7K turns a correct answer into a wrong one. If the site is known to be case insensitive, it does no harm to leave the case alone either. Some forms strip spaces and others count them; keep the answer as is unless you have tested otherwise. Our note on image CAPTCHA case sensitivity covers the details.
Should you clean up the image first?
Usually not. It is tempting to convert the picture to grayscale, raise the contrast or remove the noise lines before sending it, as you would for a local OCR library. The recognition models behind the task are built for raw CAPTCHA images, noise and all, and an aggressive filter can erase thin strokes that tell an l from an i. Send the bytes exactly as the server delivered them. The one change that can help is cropping, when the image file contains extra space or a second element such as a refresh icon; even then, crop with a margin and never scale the picture down. If a particular site keeps producing wrong answers, try the score option before touching the pixels, and compare a few results by eye to see which characters are being confused.
Using the in.php interface
Older scripts often speak the in.php style. GateSolver accepts it for text images with the methods base64 and post. With json=1 the replies are JSON, which makes parsing easy.
legacy = requests.post("https://gatesolver.com/in.php", timeout=30, data={
"key": "YOUR_API_KEY", "method": "base64", "body": b64, "json": 1}).json()
legacy_id = legacy["request"]
time.sleep(2)
check = requests.get("https://gatesolver.com/res.php", timeout=30, params={
"key": "YOUR_API_KEY", "action": "get", "id": legacy_id, "json": 1}).json()
print(check)
A real script loops on res.php while the reply is still CAPCHA_NOT_READY; the guide on moving from in.php covers that interface in full and shows how to switch to createTask when you are ready.
When answers are wrong
- The image changed. You downloaded it twice, or with a different session. Fetch it once, through the form's session.
- The image was cropped or resized. Send the original bytes, not a screenshot scaled by the browser.
- The answer is right but the form says wrong. The form's session expired while you were solving, or a hidden field was missing.
- ERROR_CAPTCHA_UNSOLVABLE. The image was blank or broken, or the confidence was below your
score. It is free; reload the form and try again.
The image to text solver page lists the current price and the typical answer time of under 1 seconds.
Common questions
Why must the image be downloaded with the same session?
The server links the drawn text to your session cookie. A different session gets a different picture, so the answer would not match.
Should I include the data:image prefix in body?
No. Send only the base64 text after the comma; the task expects raw base64 with no prefix.
What score value should I use?
Leave it out at first. Set a value between 0.8 and 1 only if you prefer an unsolvable result over a possibly wrong answer.
How often should I poll an image task?
Every second. Text images are usually answered within a few seconds, much faster than token tasks.
Is a wrong answer charged?
A task is charged when it returns text. Unsolvable images and errors are free, so sending clean original images keeps costs down.
Keep reading
- Image to Text solver$0.28 per 1,000 tasks, answers under 1 seconds.
- Image CAPTCHAClassic warped text pictures, how OCR models read them, and the case and length details that decide a match.
- Are image CAPTCHA answers case sensitive?It depends on the site: many compare case-insensitively, some do not, so test once and submit answers exactly as returned.
- Moving an in.php client to GateSolverPoint an existing in.php and res.php client at GateSolver: change the base URL, check its methods, switch on json=1.