Repository navigation
Expand file tree
/
Copy pathcaptcha_solver.py
More file actions
230 lines (192 loc) · 9.7 KB
/
Copy pathcaptcha_solver.py
File metadata and controls
230 lines (192 loc) · 9.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env python3
"""captcha_solver.py — detection + solving policy. Comments may name a site
for context; no site-specific selector or URL lives here. Per-site markers
are passed in by the caller (see BOT_CHALLENGE_MARKERS in product_parser.py)
rather than hardcoded, so this module stays reusable across the family.
Policy, matching the family's hard-won rule that "detected != blocking":
- Detection stays broad — run it on every page, unconditionally.
- A captcha WIDGET present on a page whose products are already rendered
guards nothing and is not solved: `--solve-captcha when-blocked` (the
default) only pays for a solve when `count_product_links(html) == 0`.
- A missing key or a solver-side error is a WARNING, never a crash — the
run continues, and only reports EXIT_BLOCKED if the page really was
gated (see output_writer.EXIT_BLOCKED).
- A paid solve is only bought when it can be USED and when the page's
allowance is not spent. Every call site passes the same `SolveBudget`
(one allowance per page, checked BEFORE the purchase, never reset by a
retry or a scroll round), and `can_inject=False` — which is what every
local engine in this repo passes today, because none of them injects a
token into the page — means detection is reported and nothing is
bought. A token nobody injects is money spent for nothing.
No JavaScript crosses this module's boundary: it hands back a plain
(captcha_type, sitekey, token) triple. An engine that implements injection
in its own driver's dialect would pass `can_inject=True`.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from enum import Enum
from typing import Callable, Optional, Sequence
from scraper_api_client import TwoCaptchaAuthError, TwoCaptchaClient, TwoCaptchaError
# Generic signals any family site might show. A per-site BOT_CHALLENGE_MARKERS
# list (product_parser.py) is unioned with this, never a replacement for it.
GENERIC_BOT_CHALLENGE_MARKERS: Sequence[str] = (
"cf-turnstile", "challenges.cloudflare.com", "cdn-cgi/challenge-platform",
"g-recaptcha", "recaptcha/api.js", "grecaptcha",
"h-captcha", "hcaptcha.com/1/api.js",
"px-captcha", "perimeterx",
"datadome",
"attention required", "just a moment", "verify you are human",
)
class CaptchaType(str, Enum):
CLOUDFLARE_TURNSTILE = "cloudflare_turnstile"
RECAPTCHA_V2 = "recaptcha_v2"
RECAPTCHA_V3 = "recaptcha_v3"
HCAPTCHA = "hcaptcha"
_SITEKEY_PATTERNS = {
CaptchaType.CLOUDFLARE_TURNSTILE: re.compile(
r'class="[^"]*cf-turnstile[^"]*"[^>]*data-sitekey="([^"]+)"'
),
CaptchaType.RECAPTCHA_V2: re.compile(
r'class="[^"]*g-recaptcha[^"]*"[^>]*data-sitekey="([^"]+)"'
),
CaptchaType.HCAPTCHA: re.compile(
r'class="[^"]*h-captcha[^"]*"[^>]*data-sitekey="([^"]+)"'
),
}
# v3 ships no visible widget — the sitekey rides on the loader's `render=`
# query param instead of a data-sitekey attribute.
_RECAPTCHA_V3_LOADER_RE = re.compile(r"recaptcha/api\.js\?render=([\w-]+)")
_RECAPTCHA_EXPLICIT_LOADER_RE = re.compile(r"recaptcha/api\.js\?render=explicit")
@dataclass
class CaptchaSignal:
captcha_type: CaptchaType
sitekey: Optional[str]
invisible: bool = False
# The Scraping Browser API's managed Chromium ships 2Captcha's OWN
# captcha-solving extension pre-installed (confirmed live, 2026-09-14:
# extension id kjmkgkdkpedkejedfhmfcenooemhbpbo, content scripts named
# .../captcha/{turnstile,amazon_waf,yandex,lemin}/{interceptor,hunter}.js).
# `page.content()` over --cdp-endpoint captures THOSE injected <script>
# tags too, and their src/data attributes contain marker substrings like
# "cf-turnstile" regardless of whether the actual page has a real widget —
# on a real StockX 403 that turned out to be a plain, static Cloudflare
# WAF page with no captcha at all ("Sorry, you have been blocked" — no
# `data-sitekey` anywhere), this alone made GENERIC_BOT_CHALLENGE_MARKERS
# fire and identify_widget() correctly find nothing to solve, which then
# logged as a confusing "captcha-like marker detected but no known
# widget/sitekey" rather than a clean "no captcha present". Stripped here
# so the extension's own always-there code never counts as the page's.
_EXTENSION_SCRIPT_RE = re.compile(
r'<script\b[^>]*\bchrome-extension://[^>]*>.*?</script>', re.I | re.S
)
def _strip_extension_noise(html: str) -> str:
return _EXTENSION_SCRIPT_RE.sub("", html)
def detect_from_html(html: str, extra_markers: Sequence[str] = ()) -> bool:
"""Broad detection: True if ANY known marker string appears. Cheap and
deliberately over-inclusive — see module docstring on why detection and
blocking are decided separately."""
haystack = _strip_extension_noise(html).lower()
for marker in (*GENERIC_BOT_CHALLENGE_MARKERS, *extra_markers):
if marker.lower() in haystack:
return True
return False
def identify_widget(html: str) -> Optional[CaptchaSignal]:
"""Best-effort: which widget, and its sitekey. Reconciles the v3-vs-
v2-invisible ambiguity by trusting the LOADER'S query param over any
wrapper metadata — a site can label its own wrapper "v3" while shipping
a `render=explicit` (v2-invisible) loader; sending v3 parameters for a
v2-invisible widget buys a token the site rejects. `render=<sitekey>`
means v3; `render=explicit` means v2."""
html = _strip_extension_noise(html)
m = _RECAPTCHA_V3_LOADER_RE.search(html)
if m and not _RECAPTCHA_EXPLICIT_LOADER_RE.search(html):
return CaptchaSignal(CaptchaType.RECAPTCHA_V3, sitekey=m.group(1))
for ctype, pattern in _SITEKEY_PATTERNS.items():
m = pattern.search(html)
if m:
return CaptchaSignal(ctype, sitekey=m.group(1))
return None
def _task_payload(signal: CaptchaSignal, page_url: str, *, proxyless: bool, min_score: float = 0.3) -> dict:
type_map = {
CaptchaType.CLOUDFLARE_TURNSTILE: "TurnstileTaskProxyless" if proxyless else "TurnstileTask",
CaptchaType.RECAPTCHA_V2: "RecaptchaV2TaskProxyless" if proxyless else "RecaptchaV2Task",
CaptchaType.RECAPTCHA_V3: "RecaptchaV3TaskProxyless",
CaptchaType.HCAPTCHA: "HCaptchaTaskProxyless" if proxyless else "HCaptchaTask",
}
task = {"type": type_map[signal.captcha_type], "websiteURL": page_url, "websiteKey": signal.sitekey}
if signal.captcha_type == CaptchaType.RECAPTCHA_V3:
# 2Captcha's own field name for RecaptchaV3TaskProxyless (confirmed
# against their API reference) — the token 2Captcha hands back is
# produced to clear THIS threshold; it is a solve-request input, not
# something to validate against the response afterwards. `--min-
# score` is the CLI knob; omitting it would leave 2Captcha's own
# server-side default in effect, silently, which is the same
# "documented flag nobody reads" shape this family has shipped
# before — so this module always sends one.
task["minScore"] = min_score
return task
# How many paid solves one page may buy. This repo reads one page per run
# (a scroll-virtualized grid), so this is also the per-run allowance.
SOLVES_PER_PAGE = 1
class SolveBudget:
"""One page's allowance of paid solves. Create it ONCE per page, outside
every retry and scroll loop, and hand the same object to every call
site; `spend()` is checked before each purchase."""
def __init__(self, limit: int = SOLVES_PER_PAGE):
self.limit = limit
self.spent = 0
self._reported: set = set()
def available(self) -> bool:
return self.spent < self.limit
def spend(self) -> bool:
if not self.available():
return False
self.spent += 1
return True
def first_time(self, action: str) -> bool:
"""True the first time an outcome is seen — lets a caller log a
repeated outcome once instead of on every scroll round."""
if action in self._reported:
return False
self._reported.add(action)
return True
def solve_when_blocked(
*,
client: TwoCaptchaClient,
page_url: str,
html: str,
count_product_links: Callable[[str], int],
budget: SolveBudget,
can_inject: bool,
extra_markers: Sequence[str] = (),
proxyless: bool = True,
min_score: float = 0.3,
) -> dict:
"""The default `--solve-captcha when-blocked` policy. Cheap first: count
product links on the page AS-IS — no readiness wait, no scroll — because
a page whose products are already rendered is not blocked, and running
a 20s readiness wait first would burn it even when solving is what
actually makes products appear on a page that IS gated.
"""
if not detect_from_html(html, extra_markers):
return {"action": "no_captcha_detected"}
if count_product_links(html) > 0:
return {"action": "skipped_products_present"}
signal = identify_widget(html)
if signal is None:
return {"action": "detected_unidentified_widget"}
if not can_inject:
# Nothing would put the token into the page, so buying one cannot
# clear the challenge.
return {"action": "detected_not_injectable", "captcha_type": signal.captcha_type.value}
if not budget.spend():
return {"action": "budget_exhausted", "captcha_type": signal.captcha_type.value}
try:
task = _task_payload(signal, page_url, proxyless=proxyless, min_score=min_score)
token = client.solve_and_wait(task)
return {"action": "solved", "captcha_type": signal.captcha_type.value, "token": token}
except TwoCaptchaAuthError as exc:
return {"action": "warning_no_key", "detail": str(exc)}
except TwoCaptchaError as exc:
return {"action": "warning_solver_error", "detail": str(exc)}