Python में Tenacity CAPTCHA Retry: एक नहीं, दो Decorators

Python में tenacity captcha retry में एक नहीं, दो decorators लगते हैं। पहला उस call पर लगाएँ जो CapSkip Python SDK से token लाती है, और दूसरा उस फ़ॉर्म पोस्ट पर जो उसे इस्तेमाल करता है। दोनों अलग वजहों से फेल होते हैं, और दोनों के चारों ओर एक ही decorator लगाने पर साइट के बस व्यस्त होने पर भी हर बार नया solve खर्च होता है। नीचे वे errors हैं जिन्हें retry करना ठीक है, budget के जाल, और एक async संस्करण, सब mocks के सामने मापे गए।
retries जोड़ने से पहले आपको क्या चाहिए
- Python 3.10 या नया, जो capskip 1.8.0 का घोषित न्यूनतम है, tenacity 9.2.1 और requests 2.34.2। मैंने Windows 11 पर Python 3.11.7, 3.13.7 और 3.14.0 चलाए, 3.10 नहीं। तीनों पाने के लिए python -m pip install capskip tenacity requests चलाएँ।
- Windows PC पर CapSkip, और जिस पेज को आप automate करते हैं उसका फ़ॉर्म पता।
- CapSkip तक पहुँचने का कोई ज़रिया। Local mode API को 127.0.0.1 पर रखता है, इसलिए सिर्फ़ वही PC उसे कॉल कर सकता है। Server mode उसे आपके नेटवर्क या पब्लिक IP पर सुनवाता है, जिससे दूसरी मशीन की script उसे कॉल कर सकती है। यह switch आपको यहाँ मिलेगा: सेटअप गाइड का कनेक्शन सेटिंग्स सेक्शन.
CapSkip ऐप इस PC पर जवाब नहीं दे रहा था, इसलिए मैंने दो mock servers लिखे: CapSkip की जगह एक stand-in (in.php और res.php) और reCAPTCHA v2 widget वाले एक contact form की जगह एक stand-in। नीचे की हर delay, failure और साइट का नियम मेरा अपना mock नियम है, और CapSkip के error names API docs से आए हैं, किसी असली ऐप से नहीं। संख्याएँ mock के सामने Python 3.14.0, capskip 1.8.0 और tenacity 9.2.1 की हैं। मेरा mock token तभी खर्च करता है जब वह कोई फ़ॉर्म पोस्ट process करे, इसलिए 429 या 503 उसे इस्तेमाल के लायक छोड़ देता है। असली साइट अलग हो सकती है।
कौन से CapSkip errors retry के लायक हैं
चारों exception classes CapSkipError से निकलती हैं। नीचे की पंक्तियाँ SDK source और mock से आई हैं, README से नहीं।
| क्लास | यह कब उठता है | Retry करें? |
|---|---|---|
| ValidationException | आपके PC पर कुछ भी भेजे जाने से पहले उठता है, जैसे कोई असमर्थित option। mock को 0 tasks दिखे | कभी नहीं, वही कॉल हर बार वैसे ही फेल होती है |
| ERROR_CAPTCHA_UNSOLVABLE या ERROR_NO_SLOT_AVAILABLE के साथ ApiException | एक poll का जवाब, या भरी हुई queue या request limit। docs दोनों के नाम देते हैं | हाँ, नए task के रूप में |
| किसी और कोड वाला ApiException | गलत key, गायब पेज पता या गायब sitekey। ERROR_KEY_DOES_NOT_EXIST और ERROR_PAGEURL, दोनों 1 task के बाद रुक गए | कभी नहीं |
| NetworkException | submit करते समय उठता है, जब कनेक्शन फेल हो या in.php 200 के अलावा कुछ भी जवाब दे | हाँ, कुछ बार |
| TimeoutException | polling की deadline निकल गई | ज़्यादा से ज़्यादा एक-दो बार |
predicate को तीन बातें आकार देती हैं। ApiException में कोई code attribute नहीं है, इसलिए आप message text से मेल बिठाते हैं। NetworkException सिर्फ़ submit step से बाहर आ सकता है: polling के दौरान SDK उसे निगल जाता है, क्योंकि वही class "अभी तैयार नहीं" का भी मतलब रखती है, इसलिए हर poll पर HTTP 500 देने वाला res.php recaptchaTimeout 3 के साथ 3.76 सेकंड बाद TimeoutException पर खत्म हुआ। और Windows पर refuse हुए कनेक्शन को फेल होने में 2.05 सेकंड लगे, इसलिए मरा हुआ app देर से बताता है।
TimeoutException संदेह वाली पंक्ति है। SDK में task रद्द करने वाली कोई कॉल नहीं है, इसलिए हो सकता है app छोड़े गए task पर अब भी काम कर रहा हो जबकि आपका retry दूसरा submit करता है। मैं इसे असली app पर जाँच नहीं सका, इसलिए attempt की गिनती कम रखें।
script को चार steps में बनाएँ
Step 1: पेज और solver तैयार करें
इस ब्लॉक को retry_form.py नाम से सेव करें और हर बाद वाले ब्लॉक को क्रम से इसके अंत में जोड़ें, Step 4 तक, चाहें तो naive_send छोड़ दें। किसी दूसरे PC के CapSkip तक पहुँचने के लिए host में 127.0.0.1 की जगह उस PC का पता रखें। sitekey data-sitekey attribute से आता है, इसलिए script उसे hard-code करने के बजाय पढ़ती है।
# 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: solve के लिए tenacity captcha retry
solve को एक decorator मिलता है। retry argument दो परीक्षाओं को pipe से जोड़ता है: उन classes के लिए retry_if_exception_type जो अस्थायी हैं, और उन ApiException codes के लिए retry_if_exception जिन्हें दोहराना ठीक है। अगर आपने CapSkip में unsolvable tasks के लिए replacement text सेट किया है, तो उससे भी मेल बिठाएँ। ValidationException दोनों से मेल नहीं खाती और पहली ही call पर बाहर आ जाती है। wait wait_random_exponential है, जो हर sleep को एक ऐसी window से random चुनता है जो max तक दोगुनी होती जाती है, ताकि कई workers एक ही समय पर retry न करें।
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"]reraise=True के बिना, attempts खत्म होने पर tenacity अपनी RetryError उठाता है, और SDK classes का handler कभी नहीं चलता। इसके साथ, मूल exception बाहर आती है: लगातार पाँच unsolvable जवाब 3 tasks के बाद ApiException पर खत्म हुए। हर attempt नया task है, क्योंकि result सिर्फ़ एक बार पढ़ा जा सकता है।
Step 3: फ़ॉर्म पोस्ट को अलग से retry करें
फ़ॉर्म पोस्ट अलग तरह से फेल होता है। साइट 429 या 503 दे सकती है, या कनेक्शन reset कर सकती है, और token अब भी सही हो सकता है, इसलिए सही कदम वही token दोबारा भेजना है। अगला ब्लॉक दो exception classes और एक wait function जोड़ता है। wait कोई भी callable है जो retry state लेता है और सेकंड लौटाता है। यह वाला Retry-After को तब मानता है जब header में संख्या हो, 30 सेकंड तक, और वरना jitter वाले backoff पर लौट जाता है। Retry-After एक HTTP date भी हो सकता है, जिसे यह संस्करण fallback को भेज देता है। HTTP 429 की गाइड date वाला रूप parse करती है, और MDN के दस्तावेज़ में देखें 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)यह function उन जवाबों को exceptions में बदलता है और बाकी को छोड़ देता है। 200 पेज जो कहता है कि captcha check फेल हुआ, एक response है, error नहीं, और Step 4 उसे सँभालता है।
@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 replyRetry-After 2 वाले दो 429 जवाबों ने 2.0 और 2.0 सेकंड के waits बनाए, 3 फ़ॉर्म पोस्ट और 1 solve। एक 429, एक 503 और एक reset ने 4 फ़ॉर्म पोस्ट, 1 solve और एक सेव हुआ message दिया। छह 503 जवाब 4 posts के बाद Busy के साथ रुक गए, फिर भी 1 solve। अगर किसी साइट ने request process की और सिर्फ़ जवाब खो गया, तो वही token दूसरी बार फेल होता है, जो Step 4 में एक अतिरिक्त solve खर्च कराता है।
दोनों के चारों ओर एक decorator solves क्यों खर्च कराता है
decorate किया हुआ function अपने अंदर सब कुछ फिर चलाता है। लुभावना संस्करण एक ऐसे function के चारों ओर एक decorator लगाता है जो solve करता है और फिर post करता है।
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 retryयह साफ़-सुथरा दिखता है और solves बर्बाद करता है। mock के 503 दो बार देने पर naive_send ने 3 फ़ॉर्म पोस्ट के लिए 3 solves खर्च किए, जबकि दोनों decorators ने उन्हीं 3 posts के लिए 1 solve। दो 429 जवाबों ने भी वही किया। एक solve में सेकंड लगते हैं और व्यस्त साइट कुछ नहीं लेती, इसलिए हर hiccup पूरा solve बन जाता है। nesting और बुरी है, क्योंकि attempt limits गुणा हो जाती हैं: post_form के 4 के बाहर 4 attempts ने उस mock के सामने 16 फ़ॉर्म पोस्ट और 4 solves भेजे जो हमेशा 503 देता था, तीन रन में 10 से 18 सेकंड में।
Step 4: token ठुकराए जाने पर ही दोबारा solve करें
एक failure को अब भी नया solve चाहिए: साइट ने request ले ली और token ठुकरा दिया। यह एक सामान्य पेज के रूप में आता है, इसलिए कोई decorator उसे नहीं देखता, और एक छोटा loop उसे सँभालता है। हर round नया token माँगता है, क्योंकि token सिर्फ़ एक बार इस्तेमाल होता है। इनकार की जाँच आपकी साइट का एक पूरा वाक्यांश है, सिर्फ़ शब्द captcha नहीं, जिसे widget markup दोहरा सकता है। phrase और success sign को उनसे बदलें जो आपकी साइट दिखाती है।
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"))इसे python retry_form.py से चलाएँ। tenacity captcha retry script mock के सामने वैसे ही चली जैसी यहाँ लिखी है:
| mock सेटिंग | Tasks की संख्या | फ़ॉर्म पोस्ट की संख्या | नतीजा |
|---|---|---|---|
| सब कुछ काम करता है | 1 | 1 | round 1 में सेव हुआ |
| दो ERROR_CAPTCHA_UNSOLVABLE जवाब, फिर पास | 3 | 1 | सहेजा गया |
| ERROR_CAPTCHA_UNSOLVABLE पाँच बार | 3 | 0 | ApiException |
| ERROR_KEY_DOES_NOT_EXIST | 1 | 0 | तुरंत ApiException |
| असमर्थित option | 0 | 0 | तुरंत ValidationException |
| in.php दो बार HTTP 500 देता है | 3 | 1 | सहेजा गया |
| CapSkip port पर कोई नहीं सुन रहा | 0 | 0 | 7.0 से 8.7 s बाद NetworkException |
| एक बार ERROR_NO_SLOT_AVAILABLE, फिर पास | 2 | 1 | सहेजा गया |
| साइट token को एक बार ठुकराती है | 2 | 2 | round 2 में सेव हुआ |
| साइट token को हर बार ठुकराती है | 3 | 3 | 3 rounds के बाद RuntimeError |
stop_after_delay असल में क्या bound करता है
SDK की अपनी deadline है, recaptchaTimeout (reCAPTCHA के लिए default 300 सेकंड), और tenacity के पास stop_after_delay है। दोनों में से कोई wall clock नहीं है। SDK अपनी deadline सिर्फ़ polls के बीच जाँचता है, जो 0.25 सेकंड से pollingInterval की ओर backoff करते हैं, इसलिए failure देर से आती है: कभी जवाब न देने वाले mock के सामने recaptchaTimeout 3 ने 3.76 सेकंड बाद error उठाया, 10 ने 12.77 बाद और 20 ने 22.77 बाद। 2 सेकंड बाद तैयार होने वाला pass 3.77 पर पहुँचा।
tenacity stop_after_delay को attempt खत्म होने के बाद जाँचता है, attempt के दौरान कभी नहीं। recaptchaTimeout 3, stop_after_delay(5) और 0.5 सेकंड के तय wait के साथ, दूसरा attempt करीब 4.3 सेकंड पर शुरू हुआ, budget के अंदर, और run करीब 8 पर खत्म हुआ। stop_before_delay वाला संस्करण उसी समय खत्म हुआ, क्योंकि वह attempt की लंबाई नहीं, आने वाली sleep गिनता है। recaptchaTimeout 1 के साथ वही budget करीब 6.3 पर खत्म हुआ। पहले SDK timeout का आकार तय करें और tenacity budget को एक मोटी ऊपरी सीमा की तरह पढ़ें।
sync client की समस्या ज़्यादा कठोर है: SDK requests को बिना timeout के कॉल करता है, इसलिए जो server in.php स्वीकार कर ले और कभी जवाब न दे, वह कॉल को हमेशा के लिए अटका देता है। मेरी वाली 15 सेकंड बाद भी अटकी थी, जब मैंने उसे रोका, और कोई tenacity setting चलती हुई कॉल को नहीं रोकती।
AsyncCapSkip के साथ AsyncRetrying
AsyncCapSkip httpx पर बना असली async client है, और AsyncRetrying asyncio से sleep करता है, time.sleep से नहीं। कई retrying jobs एक साथ चल सकते हैं, और हर attempt को asyncio.wait_for से कड़ी सीमा मिल सकती है, जो tenacity खुद नहीं कर सकता। कभी जवाब न देने वाले mock के सामने, 3 attempts और तय 0.5 सेकंड के wait के साथ 2 सेकंड के wait_for ने उन्हें 0, 2.5 और 5.0 सेकंड पर शुरू किया और 7.0 पर खत्म किया, SDK timeout 60 पर छोड़कर। mock ने तीनों छोड़े गए tasks रखे और असली app भी रख सकता है, इसलिए सीमा उदार रखें।
async client अपने आप भी timeout करता है। httpx default रूप से 5 सेकंड इंतज़ार करता है, इसलिए जिस चुप server ने sync client को अटकाया था उसने करीब 5.3 सेकंड बाद NetworkException उठाया, जिसे retry अस्थायी मानता है। अगले ब्लॉक को retry_async.py नाम से retry_form.py के बगल में सेव करें। एक retry object हर कॉल को सँभालता है: एक साझा AsyncRetrying से 1,200 कॉल, एक बार में 60, हर एक ने Python 3.14.0 पर सिर्फ़ tenacity वाले test में अपेक्षित attempts चलाए।
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"]attempts खत्म होने पर retry_error_callback None लौटाता है। यह यहाँ इस्तेमाल हुए call रूप में और decorator रूप में काम करता है। for attempt in AsyncRetrying वाले loop रूप में callback चलता है, लेकिन उसकी लौटाई value फेंक दी जाती है और loop बस खत्म हो जाता है। अगला ब्लॉक तीन solves एक साथ इकट्ठा करता है, फिर हर token को Step 3 के sync function से post करता है, जो इंतज़ार करते समय event loop को block करता है।
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())1 सेकंड के mock delay वाले तीन solves overlap होकर 1.7 से 2.2 सेकंड में खत्म हुए, जबकि sync client से एक के बाद एक 5.3 सेकंड में। पहला task unsolvable होने पर इसने 4 tasks इस्तेमाल किए, और तीनों फ़ॉर्म पोस्ट सेव हुए। हर attempt unsolvable होने पर, 9 tasks तीन None values पर खत्म हुए। गलत key के साथ 3 ApiException objects नतीजे के रूप में आए और कुछ retry नहीं हुआ। बड़े pool और semaphore के लिए देखें Python में captchas को parallel में हल करना.
आम errors
| लक्षण | कारण | फिक्स |
|---|---|---|
| tenacity.RetryError, SDK exception की जगह | reraise सेट नहीं है | reraise=True दें, या RetryError से last_attempt.exception() पढ़ें |
| गलत key तीन बार retry होती है | predicate हर ApiException से मेल खाती है | सिर्फ़ retry योग्य codes से मेल कराएँ, जैसा is_retryable करता है |
| run stop_after_delay से आगे निकल जाता है | जाँच attempt खत्म होने के बाद होती है | SDK timeout घटाएँ, या async कॉल को asyncio.wait_for में लपेटें |
| फ़ॉर्म पोस्ट के हर retry पर एक solve | solve और post के चारों ओर एक decorator | उन्हें अलग करें, जैसा Steps 2 और 3 में है |
| retry के दौरान event loop रुक जाता है | एक sync decorated function coroutine के अंदर sleep करता है | async client के साथ AsyncRetrying इस्तेमाल करें |
FAQ
क्या retry किसी block पेज का जवाब है?
नहीं। जो block हर attempt पर लौटता है वह एक फ़ैसला है, और request दोहराने से बस वही फ़ैसला दोहरता है। पहले जवाब को वर्गीकृत करने के लिए देखें CAPTCHA या ब्लॉक गाइड, और retry सिर्फ़ उन्हीं मामलों में करें जो अस्थायी हैं।
क्या यह दूसरे captcha types के लिए चलता है?
retry के नियम SDK exceptions पर टिके हैं, जो हर method के लिए एक जैसी हैं। solve_token के अंदर की कॉल बदलें, predicate वैसी ही रखें, और फ़ील्ड names के लिए पेज पढ़ें।
क्या मेरे retries किसी दूसरे PC के CapSkip को कॉल कर सकते हैं?
हाँ। CapSkip वाली मशीन पर Server mode चालू करें, फिर उस मशीन का पता दोनों clients में host के रूप में इस्तेमाल करें, और API Key Validation चालू हो तो अपनी key को apiKey के रूप में जोड़ें। Server mode शुरू करने से CapSkip का port हर पते के लिए खुल जाता है, इसलिए अजनबियों को बाहर रखने के लिए उनके पतों पर Windows Firewall का block rule लगाएँ। एक संकरा allow rule कुछ भी सीमित नहीं करता। बंद या पहुँच से बाहर server PC Windows पर करीब 21 सेकंड बाद NetworkException देता है (मेरी मशीन, Python 3.14.0)। सिर्फ़ वही server जो कनेक्शन स्वीकार करे और कभी जवाब न दे, sync client को हमेशा के लिए अटकाता है।
संक्षेप में
tenacity captcha retry तब काम करता है जब हर step को उसकी अपनी failures के लिए retry किया जाए: unsolvable या timeout हुए solve के लिए नया task, व्यस्त साइट के लिए वही token, और नया solve सिर्फ़ तब जब token ठुकराया जाए। आपके अपने PC पर चलने वाला फ़्लैट-लाइसेंस कैप्चा बायपास tool इसे सस्ता बना देता है, हालाँकि हर task अब भी app को व्यस्त रखता है। tenacity का documentation यहाँ इस्तेमाल हुए हर stop, wait और retry helper की सूची देता है।
