Tenacity CAPTCHA Retry in Python: Two Decorators, Not One

Tenacity captcha retry in Python takes two decorators, not one. Put the first on the call that fetches a token from the CapSkip Python SDK and the second on the form post that uses it. They fail for different reasons, and one decorator around both pays for a fresh solve whenever the site is merely busy. Below are the errors worth retrying, the budget traps and an async version, all measured against mocks.
What you need before adding retries
- Python 3.10 or newer, the minimum declared by capskip 1.8.0, tenacity 9.2.1 and requests 2.34.2. I ran Python 3.11.7, 3.13.7 and 3.14.0 on Windows 11, not 3.10. Run python -m pip install capskip tenacity requests to get all three.
- CapSkip on a Windows PC, plus the form address of the page you automate.
- Somewhere to reach CapSkip. Local mode keeps the API on 127.0.0.1, so only the same PC can call it. Server mode makes it listen on your network or public IP, which lets a script on a second machine call it. Find the switch in the connection settings section of the setup guide.
The CapSkip app did not answer on this PC, so I wrote two mock servers: a stand-in for CapSkip (in.php and res.php) and a stand-in for a contact form with a reCAPTCHA v2 widget. Every delay, failure and site rule below is my own mock rule, and the CapSkip error names come from the API docs, not from a real app. Numbers are Python 3.14.0, capskip 1.8.0 and tenacity 9.2.1 against the mock. My mock consumes a token only when it processes a form post, so a 429 or 503 leaves it usable. A real site may differ.
Which CapSkip errors deserve a retry
The four exception classes derive from CapSkipError. The rows below come from the SDK source and the mock, not from the README.
| Class | Raised when | Retry it? |
|---|---|---|
| ValidationException | Raised on your PC before anything is sent, for example an unsupported option. The mock saw 0 tasks | Never, the same call fails the same way |
| ApiException with ERROR_CAPTCHA_UNSOLVABLE or ERROR_NO_SLOT_AVAILABLE | A poll answer, or a full queue or request limit. The docs name both | Yes, as a new task |
| ApiException with any other code | A wrong key, a missing page address or a missing sitekey. ERROR_KEY_DOES_NOT_EXIST and ERROR_PAGEURL each stopped after 1 task | Never |
| NetworkException | Raised while submitting, when the connection fails or in.php answers anything but 200 | Yes, a few times |
| TimeoutException | The polling deadline passed | Once or twice at most |
Three details shape the predicate. ApiException has no code attribute, so you match the message text. NetworkException can only come out of the submit step: during polling the SDK swallows it, because the same class also means "not ready yet", so a res.php that answered HTTP 500 on every poll ended in TimeoutException after 3.76 seconds with recaptchaTimeout at 3. And a refused connection took 2.05 seconds to fail on Windows, so a dead app is slow to report.
TimeoutException is the doubtful row. The SDK has no call to cancel a task, so the app may still be working on the abandoned one while your retry submits another. I could not check that against the real app, so keep the attempt count low.
Build the script in four steps
Step 1: set up the page and the solver
Save this block as retry_form.py and add every later block at the end, in order, up to Step 4, skipping naive_send if you like. To reach a CapSkip on another PC, replace 127.0.0.1 in host with that PC’s address. The sitekey comes from the data-sitekey attribute, so the script reads it instead of hard-coding it.
# python -m pip install capskip tenacity requests
import re
import requests
from capskip import ApiException, CapSkip, NetworkException, TimeoutException
from tenacity import (
retry,
retry_if_exception,
retry_if_exception_type,
stop_after_attempt,
stop_after_delay,
wait_random_exponential,
)
FORM_URL = "https://example.com/contact" # the page that shows the widget
SUBMIT_URL = "https://example.com/contact/send" # the form's action address
# Local mode. In Server mode, use the address of the CapSkip machine.
solver = CapSkip(host="127.0.0.1", port=8080, recaptchaTimeout=60)
def open_form():
session = requests.Session()
page = session.get(FORM_URL, timeout=15) # cookies arrive with the page
page.raise_for_status()
found = re.search(r'data-sitekey=["\']([^"\']+)["\']', page.text)
if not found:
raise RuntimeError("no data-sitekey on the page")
return session, found.group(1)Step 2: the tenacity captcha retry for the solve
The solve gets one decorator. The retry argument joins two tests with a pipe: retry_if_exception_type for the classes that are transient, and retry_if_exception for the ApiException codes worth repeating. If you set replacement text for unsolvable tasks in CapSkip, match it too. ValidationException matches neither and surfaces on the first call. The wait is wait_random_exponential, which draws each sleep at random from a window that doubles up to the max, so several workers don’t retry in step.
RETRY_CODES = ("ERROR_CAPTCHA_UNSOLVABLE", "ERROR_NO_SLOT_AVAILABLE")
def is_retryable(err):
# ApiException has no code attribute: the code is in the message text.
return isinstance(err, ApiException) and any(c in str(err) for c in RETRY_CODES)
def say_retry(state):
err = state.outcome.exception()
wait = state.next_action.sleep
print(f" attempt {state.attempt_number}: {type(err).__name__}, sleeping {wait:.1f}s")
@retry(
retry=retry_if_exception_type((NetworkException, TimeoutException))
| retry_if_exception(is_retryable), # ValidationException is not listed
stop=stop_after_attempt(3) | stop_after_delay(120),
wait=wait_random_exponential(multiplier=1, max=20), # full jitter
before_sleep=say_retry,
reraise=True, # raise the SDK error itself, not tenacity.RetryError
)
def solve_token(sitekey):
# Every attempt is a NEW task: a result can be read only once.
return solver.recaptcha(sitekey, FORM_URL)["code"]Without reraise=True, tenacity raises its own RetryError once the attempts run out, and a handler for the SDK classes never fires. With it, the original exception comes out: five unsolvable answers in a row ended in ApiException after 3 tasks. Every attempt is a new task, because a result can be read only once.
Step 3: retry the form post on its own
A form post fails differently. The site can answer 429 or 503, or reset the connection, and the token may still be good, so the right move is to send the same token again. The next block adds two exception classes and a wait function. A wait is any callable that takes the retry state and returns seconds. This one obeys Retry-After when the header holds a number, up to 30 seconds, and otherwise falls back to the jittered backoff. A Retry-After can also be an HTTP date, which this version sends to the fallback. The guide to HTTP 429 parses the date form, and MDN documents the Retry-After header.
class RateLimited(Exception):
def __init__(self, seconds):
super().__init__(f"429, Retry-After {seconds}")
self.seconds = seconds # None when the header is missing or a date
class Busy(Exception):
pass
jitter = wait_random_exponential(multiplier=1, max=20)
def wait_for_form(state):
err = state.outcome.exception()
if isinstance(err, RateLimited) and err.seconds is not None:
return min(err.seconds, 30) # obey Retry-After, up to a ceiling
return jitter(state)The function turns those answers into exceptions and leaves the rest alone. A 200 page that says the captcha check failed is a response, not an error, and Step 4 handles it.
@retry(
retry=retry_if_exception_type(
(requests.ConnectionError, requests.Timeout, RateLimited, Busy)
),
stop=stop_after_attempt(4),
wait=wait_for_form,
before_sleep=say_retry,
reraise=True,
)
def post_form(session, token, name, message):
reply = session.post(
SUBMIT_URL,
data={"name": name, "message": message, "g-recaptcha-response": token},
headers={"Referer": FORM_URL}, # requests sends none by itself
timeout=15,
)
if reply.status_code == 429:
raw = reply.headers.get("Retry-After", "")
raise RateLimited(int(raw) if raw.isdigit() else None)
if reply.status_code in (502, 503, 504):
raise Busy(f"HTTP {reply.status_code}")
return replyTwo 429 answers with Retry-After set to 2 produced waits of 2.0 and 2.0 seconds, 3 form posts and 1 solve. A 429, a 503 and a reset gave 4 form posts, 1 solve and a saved message. Six 503 answers stopped after 4 posts with Busy, still 1 solve. If a site processed a request and lost only the reply, the same token fails the second time, which costs one extra solve in Step 4.
Why one decorator around both costs solves
A decorated function re-runs everything inside it. The tempting version puts one decorator around a function that solves and then posts.
from tenacity import wait_fixed
@retry(
retry=retry_if_exception_type((NetworkException, TimeoutException, RateLimited, Busy)),
stop=stop_after_attempt(4),
wait=wait_fixed(1),
reraise=True,
)
def naive_send(session, sitekey, name, message):
token = solver.recaptcha(sitekey, FORM_URL)["code"] # runs again on every retry
return post_form.__wrapped__(session, token, name, message) # no inner retryIt looks tidy and wastes solves. With the mock answering 503 twice, naive_send used 3 solves for 3 form posts, where the two decorators used 1 solve for the same 3 posts. Two 429 answers did the same. A solve takes seconds and a busy site takes none, so every blip becomes a full solve. Nesting is worse, because attempt limits multiply: an outer 4 attempts around the 4 of post_form sent 16 form posts and 4 solves against a mock that always answered 503, in 10 to 18 seconds across three runs.
Step 4: solve again only when the token is refused
One failure still needs a new solve: the site took the request and refused the token. That arrives as an ordinary page, so no decorator sees it, and a short loop handles it. Each round asks for a fresh token, because a token is single use. The refusal test is a whole phrase from your site, not the bare word captcha, which the widget markup may repeat. Replace the phrase and the success sign with the ones your site shows.
def send_message(name, message, rounds=3):
session, sitekey = open_form()
for number in range(1, rounds + 1):
token = solve_token(sitekey) # a fresh token for every round
reply = post_form(session, token, name, message) # same token inside
if "Message saved" in reply.text: # your site's success sign
return number
if "captcha check failed" not in reply.text.lower(): # your phrase
raise RuntimeError(f"refused ({reply.status_code}), not the captcha")
print(f" round {number}: token refused, solving again")
raise RuntimeError(f"token refused {rounds} times")
if __name__ == "__main__":
print("saved in round", send_message("alice", "Hello"))Run it with python retry_form.py. The tenacity captcha retry script ran as written here against the mock:
| Mock setting | Tasks | Form posts | Result |
|---|---|---|---|
| Everything works | 1 | 1 | Saved in round 1 |
| Two ERROR_CAPTCHA_UNSOLVABLE answers, then a pass | 3 | 1 | Saved |
| ERROR_CAPTCHA_UNSOLVABLE five times | 3 | 0 | ApiException |
| ERROR_KEY_DOES_NOT_EXIST | 1 | 0 | ApiException at once |
| An unsupported option | 0 | 0 | ValidationException at once |
| in.php answers HTTP 500 twice | 3 | 1 | Saved |
| Nothing listens on the CapSkip port | 0 | 0 | NetworkException after 7.0 to 8.7 s |
| ERROR_NO_SLOT_AVAILABLE once, then a pass | 2 | 1 | Saved |
| Site refuses the token once | 2 | 2 | Saved in round 2 |
| Site refuses the token every time | 3 | 3 | RuntimeError after 3 rounds |
What stop_after_delay really bounds
The SDK has its own deadline, recaptchaTimeout (300 seconds by default for reCAPTCHA), and tenacity has stop_after_delay. Neither is a wall clock. The SDK checks its deadline only between polls, which back off from 0.25 seconds toward pollingInterval, so the failure lands late: with a mock that never answered, recaptchaTimeout of 3 raised after 3.76 seconds, 10 after 12.77 and 20 after 22.77. A pass ready after 2 seconds arrived at 3.77.
Tenacity checks stop_after_delay after an attempt ends, never during one. With recaptchaTimeout at 3, stop_after_delay(5) and a fixed 0.5 second wait, the second attempt began at about 4.3 seconds, inside the budget, and the run ended at about 8. The stop_before_delay variant ended at the same time, because it counts the coming sleep, not the length of the attempt. With recaptchaTimeout at 1 the same budget ended at about 6.3. Size the SDK timeout first and read the tenacity budget as a rough ceiling.
The sync client has a harder problem: the SDK calls requests without a timeout, so a server that accepts in.php and never replies blocks the call for good. Mine was still blocked after 15 seconds, when I stopped it, and no tenacity setting interrupts a running call.
AsyncRetrying with AsyncCapSkip
AsyncCapSkip is a real async client built on httpx, and AsyncRetrying sleeps with asyncio, not time.sleep. Many retrying jobs can run at once, and each attempt can get a hard limit from asyncio.wait_for, which tenacity cannot do itself. Against a mock that never answered, a 2 second wait_for with 3 attempts and a fixed 0.5 second wait started them at 0, 2.5 and 5.0 seconds and ended at 7.0, with the SDK timeout left at 60. The mock kept all three abandoned tasks and the real app may too, so keep the limit generous.
The async client also times out by itself. httpx waits 5 seconds by default, so the silent server that blocked the sync client raised NetworkException after about 5.3 seconds, which the retry treats as transient. Save the next block as retry_async.py beside retry_form.py. One retry object serves every call: 1,200 calls through one shared AsyncRetrying, 60 at a time, each ran the expected number of attempts in a tenacity-only test on Python 3.14.0.
import asyncio
from capskip import AsyncCapSkip, NetworkException, TimeoutException
from tenacity import (
AsyncRetrying,
retry_if_exception,
retry_if_exception_type,
stop_after_attempt,
stop_after_delay,
wait_random_exponential,
)
from retry_form import FORM_URL, is_retryable, open_form, post_form, say_retry
# Local mode. In Server mode, use the address of the CapSkip machine.
async_solver = AsyncCapSkip(host="127.0.0.1", port=8080)
solve_retrying = AsyncRetrying(
retry=retry_if_exception_type(
(NetworkException, TimeoutException, asyncio.TimeoutError)
)
| retry_if_exception(is_retryable),
stop=stop_after_attempt(3) | stop_after_delay(120),
wait=wait_random_exponential(multiplier=1, max=20),
before_sleep=say_retry,
retry_error_callback=lambda state: None, # give up with None, no RetryError
)
async def one_attempt(sitekey):
# A hard cap for one attempt: the SDK looks at its own deadline only
# at the next poll, and tenacity cannot interrupt a running attempt.
result = await asyncio.wait_for(async_solver.recaptcha(sitekey, FORM_URL), 45)
return result["code"]The retry_error_callback returns None when the attempts run out. That works in the call form used here and in the decorator form. In the for attempt in AsyncRetrying loop form the callback runs, but its return value is thrown away and the loop just ends. The next block collects three solves at once, then posts each token with the sync function from Step 3, which blocks the event loop while it waits.
async def solve_many(sitekey, count):
jobs = [solve_retrying(one_attempt, sitekey) for _ in range(count)]
return await asyncio.gather(*jobs, return_exceptions=True)
async def main():
session, sitekey = open_form()
outcomes = await solve_many(sitekey, 3)
for number, token in enumerate(outcomes, 1):
if not isinstance(token, str):
print(f"form {number}: no token ({token!r})")
continue
reply = post_form(session, token, f"alice{number}", "Hello")
print(f"form {number}:", "saved" if "Message saved" in reply.text else "refused")
if __name__ == "__main__":
asyncio.run(main())Three solves with a mock delay of 1 second finished in 1.7 to 2.2 seconds overlapped, against 5.3 seconds one after another with the sync client. With the first task unsolvable it used 4 tasks, and all three form posts were saved. With every attempt unsolvable, 9 tasks ended in three None values. With a wrong key, 3 ApiException objects came back as results and nothing was retried. For a bigger pool and a semaphore, see solving captchas in parallel with Python.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| tenacity.RetryError instead of an SDK exception | reraise is not set | Pass reraise=True, or read last_attempt.exception() from the RetryError |
| A wrong key is retried three times | The predicate matches every ApiException | Match only the retryable codes, as is_retryable does |
| The run outlasts stop_after_delay | The check happens after an attempt ends | Lower the SDK timeout, or wrap the async call in asyncio.wait_for |
| One solve per form post retry | One decorator around solve and post | Split them, as in Steps 2 and 3 |
| The event loop stalls during a retry | A sync decorated function sleeps inside a coroutine | Use AsyncRetrying with the async client |
FAQ
Is a retry the answer to a block page?
No. A block that comes back on every attempt is a decision, and repeating the request only repeats it. Classify the answer first with the CAPTCHA or block guide, and retry only the cases that are transient.
Does this work for other captcha types?
The retry rules rest on the SDK exceptions, which are the same for every method. Swap the call inside solve_token, keep the predicate, and read the page for its own field names.
Can my retries call a CapSkip on a second PC?
Yes. On the CapSkip machine, switch to Server mode, then use that machine’s address as host in both clients, adding your key as apiKey when API Key Validation is on. Starting Server mode opens the CapSkip port to any address, so keep strangers out with a Windows Firewall block rule for their addresses. A narrower allow rule would restrict nothing. A switched-off or unreachable server PC gives a NetworkException after about 21 seconds on Windows (my machine, Python 3.14.0). Only a server that accepts the connection and never replies blocks the sync client for good.
The short version
A tenacity captcha retry works when each step is retried for its own failures: a new task for an unsolvable or timed-out solve, the same token for a busy site, a fresh solve only when the token is refused. A flat-license captcha bypass tool on your own PC makes that cheap to do, though each task still occupies the app. The tenacity documentation lists every stop, wait and retry helper used here.
