cloudscraper-turnstile 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ """cloudscraper-turnstile: a cloudscraper drop-in that solves Cloudflare
2
+ Turnstile and the 5s interstitial through the Peak API.
3
+
4
+ Swap two lines and existing code keeps working::
5
+
6
+ import cloudscraper_turnstile as cloudscraper
7
+
8
+ scraper = cloudscraper.create_scraper(api_key="pk_your_api_key")
9
+ r = scraper.get("https://protected.example.com/")
10
+ print(r.status_code, r.text)
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from .detect import (
16
+ extract_sitekey,
17
+ extract_turnstile_fields,
18
+ is_cloudflare_challenge,
19
+ is_interstitial_challenge,
20
+ is_turnstile_challenge,
21
+ )
22
+ from .peak import (
23
+ PeakClient,
24
+ PeakError,
25
+ build_cloudflare5s_payload,
26
+ build_turnstile_payload,
27
+ )
28
+ from .scraper import CloudScraper, create_scraper, resolve_api_key
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ __all__ = [
33
+ "create_scraper",
34
+ "CloudScraper",
35
+ "resolve_api_key",
36
+ "PeakClient",
37
+ "PeakError",
38
+ "build_turnstile_payload",
39
+ "build_cloudflare5s_payload",
40
+ "is_cloudflare_challenge",
41
+ "is_turnstile_challenge",
42
+ "is_interstitial_challenge",
43
+ "extract_sitekey",
44
+ "extract_turnstile_fields",
45
+ "__version__",
46
+ ]
@@ -0,0 +1,114 @@
1
+ """Cloudflare challenge detection and field extraction.
2
+
3
+ Pure functions, no requests/session dependency, so they are cheap to test.
4
+ Handles both the interactive Turnstile widget and the non-interactive 5s
5
+ "Just a moment..." interstitial.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import Optional
12
+
13
+ # Markers that a response is a Cloudflare challenge page rather than real
14
+ # content. Split so we can tell a Turnstile widget apart from the 5s page.
15
+ _TURNSTILE_MARKERS = (
16
+ "cf-turnstile",
17
+ "challenges.cloudflare.com/turnstile",
18
+ "turnstile.render",
19
+ "data-sitekey",
20
+ )
21
+ _INTERSTITIAL_MARKERS = (
22
+ "just a moment",
23
+ "cf_chl_opt",
24
+ "window._cf_chl_opt",
25
+ "__cf_chl",
26
+ "/cdn-cgi/challenge-platform",
27
+ "cf-challenge-running",
28
+ )
29
+
30
+ # Statuses Cloudflare typically serves a challenge on. Not required (the body
31
+ # marker decides), but used to raise confidence.
32
+ CHALLENGE_STATUSES = frozenset({403, 429, 503})
33
+
34
+ # data-sitekey="0x4AAAAA..." (the widget div attribute)
35
+ _SITEKEY_ATTR = re.compile(r"""data-sitekey\s*=\s*["']([^"']+)["']""", re.I)
36
+ # turnstile.render('#el', { sitekey: '0x4AAAAA...' }) or sitekey: "0x..."
37
+ _SITEKEY_JS = re.compile(r"""(?:sitekey|render)\s*[:=]\s*["']([^"']+)["']""", re.I)
38
+ # data-cdata="..." / cData: "..."
39
+ _CDATA = re.compile(r"""(?:data-cdata|cdata|cData)\s*[:=]\s*["']([^"']+)["']""", re.I)
40
+ # data-action="..." / action: "..."
41
+ _ACTION = re.compile(r"""(?:data-action|action)\s*[:=]\s*["']([^"']+)["']""", re.I)
42
+ # data-pagedata / chlPageData
43
+ _PAGEDATA = re.compile(
44
+ r"""(?:data-pagedata|pagedata|chlPageData)\s*[:=]\s*["']([^"']+)["']""", re.I
45
+ )
46
+
47
+
48
+ def is_turnstile_challenge(body_text: str, status: Optional[int] = None) -> bool:
49
+ """Return True if the response looks like a Turnstile widget challenge."""
50
+ if not body_text:
51
+ return False
52
+ lowered = body_text.lower()
53
+ return any(marker in lowered for marker in _TURNSTILE_MARKERS)
54
+
55
+
56
+ def is_interstitial_challenge(body_text: str, status: Optional[int] = None) -> bool:
57
+ """Return True if the response looks like the 5s "Just a moment" page."""
58
+ if not body_text:
59
+ return False
60
+ lowered = body_text.lower()
61
+ return any(marker in lowered for marker in _INTERSTITIAL_MARKERS)
62
+
63
+
64
+ def is_cloudflare_challenge(body_text: str, status: Optional[int] = None) -> bool:
65
+ """Return True for either a Turnstile widget or the 5s interstitial."""
66
+ return is_turnstile_challenge(body_text, status) or is_interstitial_challenge(
67
+ body_text, status
68
+ )
69
+
70
+
71
+ def extract_sitekey(body_text: str) -> Optional[str]:
72
+ """Pull the Turnstile sitekey out of a challenge page, or None."""
73
+ if not body_text:
74
+ return None
75
+ match = _SITEKEY_ATTR.search(body_text)
76
+ if match:
77
+ return match.group(1).strip()
78
+ match = _SITEKEY_JS.search(body_text)
79
+ if match:
80
+ candidate = match.group(1).strip()
81
+ # Turnstile sitekeys start with 0x (1x for the test keys); guard
82
+ # against matching unrelated JS keys named "sitekey".
83
+ if candidate.startswith(("0x", "1x", "2x", "3x")):
84
+ return candidate
85
+ return None
86
+
87
+
88
+ def _first(pattern: "re.Pattern[str]", body_text: str) -> Optional[str]:
89
+ match = pattern.search(body_text)
90
+ return match.group(1).strip() if match else None
91
+
92
+
93
+ def extract_turnstile_fields(body_text: str) -> dict:
94
+ """Return {sitekey, cdata, action, pagedata} scraped from the page.
95
+
96
+ Keys are omitted when absent so the result can be splatted into the Peak
97
+ payload builder.
98
+ """
99
+ if not body_text:
100
+ return {}
101
+ fields = {}
102
+ sitekey = extract_sitekey(body_text)
103
+ if sitekey:
104
+ fields["sitekey"] = sitekey
105
+ cdata = _first(_CDATA, body_text)
106
+ if cdata:
107
+ fields["cdata"] = cdata
108
+ action = _first(_ACTION, body_text)
109
+ if action:
110
+ fields["action"] = action
111
+ pagedata = _first(_PAGEDATA, body_text)
112
+ if pagedata:
113
+ fields["pagedata"] = pagedata
114
+ return fields
@@ -0,0 +1,158 @@
1
+ """Peak API client for solving Cloudflare Turnstile and the 5s interstitial.
2
+
3
+ The whole Peak HTTP call is isolated in :meth:`PeakClient._post` so tests can
4
+ monkeypatch a single method and never touch the network. ``requests`` is used
5
+ for the call because it is already a hard dependency of this package (a
6
+ cloudscraper drop-in always has it).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Optional
12
+
13
+ import requests
14
+
15
+ DEFAULT_API_URL = "https://api.peak.fo/solve"
16
+
17
+ # task_type sent to Peak for the interactive Turnstile widget challenge.
18
+ TASK_TURNSTILE = "turnstiletask"
19
+ # task_type for the non-interactive "Just a moment..." 5s interstitial.
20
+ TASK_CLOUDFLARE_5S = "cloudflare5stask"
21
+
22
+
23
+ class PeakError(RuntimeError):
24
+ """Raised when Peak cannot solve the challenge or the call fails."""
25
+
26
+
27
+ def build_turnstile_payload(
28
+ sitekey: str,
29
+ url: str,
30
+ proxy: Optional[str] = None,
31
+ cdata: Optional[str] = None,
32
+ action: Optional[str] = None,
33
+ pagedata: Optional[str] = None,
34
+ ) -> dict:
35
+ """Build the JSON body for a Turnstile solve.
36
+
37
+ ``proxy`` and the optional ``cData`` / ``action`` / ``pagedata`` fields are
38
+ omitted entirely when not provided, per the Peak contract.
39
+ """
40
+ payload = {
41
+ "task_type": TASK_TURNSTILE,
42
+ "sitekey": sitekey,
43
+ "url": url,
44
+ }
45
+ if proxy:
46
+ payload["proxy"] = proxy
47
+ if cdata:
48
+ payload["cdata"] = cdata
49
+ if action:
50
+ payload["action"] = action
51
+ if pagedata:
52
+ payload["pagedata"] = pagedata
53
+ return payload
54
+
55
+
56
+ def build_cloudflare5s_payload(url: str, proxy: Optional[str] = None) -> dict:
57
+ """Build the JSON body for a 5s interstitial solve (no sitekey)."""
58
+ payload = {
59
+ "task_type": TASK_CLOUDFLARE_5S,
60
+ "url": url,
61
+ }
62
+ if proxy:
63
+ payload["proxy"] = proxy
64
+ return payload
65
+
66
+
67
+ class PeakClient:
68
+ """Thin client around the Peak solve endpoint."""
69
+
70
+ def __init__(
71
+ self,
72
+ api_key: str,
73
+ api_url: str = DEFAULT_API_URL,
74
+ proxy: Optional[str] = None,
75
+ timeout: float = 180.0,
76
+ ) -> None:
77
+ if not api_key:
78
+ raise PeakError(
79
+ "No Peak API key. Pass api_key=... , captcha={'provider':'peak',"
80
+ " 'api_key':...}, or set PEAK_API_KEY. Get a free key at "
81
+ "https://peak.fo."
82
+ )
83
+ self.api_key = api_key
84
+ self.api_url = api_url
85
+ self.proxy = proxy
86
+ self.timeout = timeout
87
+
88
+ def _post(self, payload: dict) -> dict:
89
+ """Send the payload to Peak and return the parsed JSON response.
90
+
91
+ Isolated so tests can monkeypatch exactly one method instead of the
92
+ network transport.
93
+ """
94
+ try:
95
+ resp = requests.post(
96
+ self.api_url,
97
+ json=payload,
98
+ headers={
99
+ "Content-Type": "application/json",
100
+ "X-API-Key": self.api_key,
101
+ },
102
+ timeout=self.timeout,
103
+ )
104
+ except requests.RequestException as exc: # pragma: no cover - network
105
+ raise PeakError(f"Peak request failed: {exc}") from exc
106
+ try:
107
+ return resp.json()
108
+ except ValueError as exc: # pragma: no cover - defensive
109
+ raise PeakError(
110
+ f"Peak returned non-JSON response: {resp.text!r}"
111
+ ) from exc
112
+
113
+ def _check(self, result: dict) -> dict:
114
+ if not result.get("success"):
115
+ raise PeakError(result.get("error") or "Peak solve failed")
116
+ data = result.get("data")
117
+ if not data:
118
+ raise PeakError("Peak response missing data")
119
+ return data
120
+
121
+ def solve_turnstile(
122
+ self,
123
+ sitekey: str,
124
+ url: str,
125
+ proxy: Optional[str] = None,
126
+ cdata: Optional[str] = None,
127
+ action: Optional[str] = None,
128
+ pagedata: Optional[str] = None,
129
+ ) -> str:
130
+ """Solve a Turnstile challenge and return the token string.
131
+
132
+ Raises :class:`PeakError` on failure.
133
+ """
134
+ payload = build_turnstile_payload(
135
+ sitekey,
136
+ url,
137
+ proxy=proxy or self.proxy,
138
+ cdata=cdata,
139
+ action=action,
140
+ pagedata=pagedata,
141
+ )
142
+ data = self._check(self._post(payload))
143
+ token = data.get("token")
144
+ if not token:
145
+ raise PeakError("Peak response missing data.token")
146
+ return token
147
+
148
+ def solve_cloudflare5s(
149
+ self, url: str, proxy: Optional[str] = None
150
+ ) -> dict:
151
+ """Solve the 5s interstitial.
152
+
153
+ Returns the full ``data`` dict from Peak, which carries a ``cookies``
154
+ map (with ``cf_clearance``) and optionally ``headers`` / ``user_agent``
155
+ to reuse on the crawl session.
156
+ """
157
+ payload = build_cloudflare5s_payload(url, proxy=proxy or self.proxy)
158
+ return self._check(self._post(payload))
@@ -0,0 +1,256 @@
1
+ """Drop-in cloudscraper replacement that actually solves Turnstile.
2
+
3
+ ``CloudScraper`` subclasses :class:`requests.Session`, so ``.get`` / ``.post`` /
4
+ ``.request`` / ``.cookies`` / ``.headers`` all behave exactly like the real
5
+ cloudscraper object. The only added behaviour is in :meth:`CloudScraper.request`:
6
+ if a response is a Cloudflare challenge (Turnstile widget or the 5s
7
+ interstitial), it is solved through the Peak API and the request is retried
8
+ transparently, returning the final real :class:`requests.Response`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import re
15
+ from typing import Optional
16
+ from urllib.parse import urljoin
17
+
18
+ import requests
19
+
20
+ from . import detect
21
+ from .peak import PeakClient, PeakError
22
+
23
+ __all__ = [
24
+ "CloudScraper",
25
+ "create_scraper",
26
+ "resolve_api_key",
27
+ "PeakError",
28
+ ]
29
+
30
+ # Cloudflare challenge forms carry these hidden fields; we resubmit the form
31
+ # with the solved token added as cf-turnstile-response.
32
+ _FORM_RE = re.compile(r"<form[^>]*>(.*?)</form>", re.IGNORECASE | re.DOTALL)
33
+ _FORM_TAG_RE = re.compile(r"<form([^>]*)>", re.IGNORECASE)
34
+ _ACTION_RE = re.compile(r"""action\s*=\s*["']([^"']*)["']""", re.IGNORECASE)
35
+ _METHOD_RE = re.compile(r"""method\s*=\s*["']([^"']*)["']""", re.IGNORECASE)
36
+ _INPUT_RE = re.compile(r"<input\b([^>]*)>", re.IGNORECASE)
37
+ _NAME_RE = re.compile(r"""name\s*=\s*["']([^"']*)["']""", re.IGNORECASE)
38
+ _VALUE_RE = re.compile(r"""value\s*=\s*["']([^"']*)["']""", re.IGNORECASE)
39
+
40
+
41
+ def resolve_api_key(api_key=None, captcha=None) -> Optional[str]:
42
+ """Resolve the Peak API key. Precedence: explicit > captcha dict > env.
43
+
44
+ Accepts cloudscraper's own captcha-provider style,
45
+ ``captcha={'provider': 'peak', 'api_key': 'pk_...'}``, so migration is a
46
+ no-op for users who already configured a captcha provider.
47
+ """
48
+ if api_key:
49
+ return api_key
50
+ if isinstance(captcha, dict):
51
+ key = captcha.get("api_key") or captcha.get("key") or captcha.get("apikey")
52
+ if key:
53
+ return key
54
+ return os.environ.get("PEAK_API_KEY")
55
+
56
+
57
+ def _parse_challenge_form(html: str, page_url: str):
58
+ """Return (action_url, method, data) for the first form on the page.
59
+
60
+ Falls back to a POST back to ``page_url`` with no hidden fields when the
61
+ page has no parseable form.
62
+ """
63
+ action_url, method, data = page_url, "POST", {}
64
+ form = _FORM_RE.search(html or "")
65
+ if form:
66
+ tag = _FORM_TAG_RE.search(html[: form.start() + 200])
67
+ attrs = tag.group(1) if tag else ""
68
+ m_action = _ACTION_RE.search(attrs)
69
+ if m_action and m_action.group(1):
70
+ action_url = urljoin(page_url, m_action.group(1))
71
+ m_method = _METHOD_RE.search(attrs)
72
+ if m_method and m_method.group(1):
73
+ method = m_method.group(1).upper()
74
+ for inp in _INPUT_RE.finditer(form.group(1)):
75
+ body = inp.group(1)
76
+ m_name = _NAME_RE.search(body)
77
+ if not m_name:
78
+ continue
79
+ m_value = _VALUE_RE.search(body)
80
+ data[m_name.group(1)] = m_value.group(1) if m_value else ""
81
+ return action_url, method, data
82
+
83
+
84
+ class CloudScraper(requests.Session):
85
+ """A ``requests.Session`` that solves Cloudflare challenges via Peak."""
86
+
87
+ def __init__(
88
+ self,
89
+ api_key: Optional[str] = None,
90
+ proxy: Optional[str] = None,
91
+ max_solve_attempts: int = 3,
92
+ debug: bool = False,
93
+ peak_client: Optional[PeakClient] = None,
94
+ **kwargs,
95
+ ) -> None:
96
+ # requests.Session.__init__ takes no arguments; swallow every extra
97
+ # cloudscraper kwarg (browser, delay, interpreter, allow_brotli, ...)
98
+ # so existing create_scraper(...) calls keep working unchanged.
99
+ super().__init__()
100
+ self.peak_api_key = api_key
101
+ self.peak_proxy = proxy
102
+ self.max_solve_attempts = max_solve_attempts
103
+ self.debug = debug
104
+ self._peak_client = peak_client
105
+ # Kept only for introspection / drop-in parity; not otherwise used.
106
+ self.cloudscraper_kwargs = dict(kwargs)
107
+
108
+ # -- Peak plumbing ----------------------------------------------------
109
+
110
+ def _get_peak(self) -> PeakClient:
111
+ """Build the Peak client lazily so a scraper can exist without a key
112
+ until a challenge actually needs solving."""
113
+ if self._peak_client is None:
114
+ self._peak_client = PeakClient(
115
+ api_key=self.peak_api_key, proxy=self._peak_proxy()
116
+ )
117
+ return self._peak_client
118
+
119
+ def _peak_proxy(self) -> Optional[str]:
120
+ """The proxy string forwarded to Peak so the solve matches the crawl
121
+ IP. Explicit ``proxy`` wins; otherwise the session's configured proxy."""
122
+ if self.peak_proxy:
123
+ return self.peak_proxy
124
+ proxies = getattr(self, "proxies", None) or {}
125
+ return proxies.get("https") or proxies.get("http") or None
126
+
127
+ def _log(self, message: str) -> None:
128
+ if self.debug:
129
+ print(f"[cloudscraper-turnstile] {message}")
130
+
131
+ # -- Challenge handling ----------------------------------------------
132
+
133
+ def _is_challenge(self, response) -> bool:
134
+ text = response.text or ""
135
+ status = response.status_code
136
+ if detect.is_interstitial_challenge(text, status):
137
+ return True
138
+ # A Turnstile widget on a normal 200 page is a real login form, not a
139
+ # block; only treat it as a challenge on a challenge status.
140
+ if detect.is_turnstile_challenge(text, status) and (
141
+ status in detect.CHALLENGE_STATUSES
142
+ ):
143
+ return True
144
+ return False
145
+
146
+ def request(self, method, url, *args, **kwargs): # type: ignore[override]
147
+ """Perform the request; solve and retry on a Cloudflare challenge."""
148
+ response = super().request(method, url, *args, **kwargs)
149
+ attempts = 0
150
+ while attempts < self.max_solve_attempts and self._is_challenge(response):
151
+ attempts += 1
152
+ self._log(
153
+ f"challenge detected (status {response.status_code}), "
154
+ f"solve attempt {attempts}/{self.max_solve_attempts}"
155
+ )
156
+ solved = self._solve_and_retry(method, url, response, kwargs)
157
+ if solved is None:
158
+ break
159
+ response = solved
160
+ return response
161
+
162
+ def _solve_and_retry(self, method, url, response, kwargs):
163
+ text = response.text or ""
164
+ proxy = self._peak_proxy()
165
+ fields = detect.extract_turnstile_fields(text)
166
+ if detect.is_turnstile_challenge(text) and fields.get("sitekey"):
167
+ token = self._get_peak().solve_turnstile(
168
+ sitekey=fields["sitekey"],
169
+ url=url,
170
+ proxy=proxy,
171
+ cdata=fields.get("cdata"),
172
+ action=fields.get("action"),
173
+ pagedata=fields.get("pagedata"),
174
+ )
175
+ self._log("turnstile token received, resubmitting challenge form")
176
+ return self._submit_turnstile(url, text, token)
177
+ # No Turnstile sitekey => the 5s interstitial path.
178
+ data = self._get_peak().solve_cloudflare5s(url, proxy=proxy)
179
+ self._log("5s clearance received, applying cookies and re-requesting")
180
+ self._apply_clearance(data)
181
+ return super().request(method, url, **kwargs)
182
+
183
+ def _submit_turnstile(self, page_url, html, token):
184
+ """Inject the token as cf-turnstile-response and resubmit the form."""
185
+ action_url, form_method, data = _parse_challenge_form(html, page_url)
186
+ data["cf-turnstile-response"] = token
187
+ # Some Cloudflare forms read the token under the g-recaptcha field too.
188
+ data.setdefault("g-recaptcha-response", token)
189
+ if form_method == "GET":
190
+ return super().request("GET", action_url, params=data)
191
+ return super().request("POST", action_url, data=data)
192
+
193
+ def _apply_clearance(self, data: dict) -> None:
194
+ """Persist cf_clearance cookies (and any returned headers / UA) so the
195
+ re-request and every later request carry them."""
196
+ cookies = data.get("cookies") or {}
197
+ for name, value in cookies.items():
198
+ self.cookies.set(name, value)
199
+ clearance = data.get("cf_clearance")
200
+ if clearance:
201
+ self.cookies.set("cf_clearance", clearance)
202
+ headers = data.get("headers") or {}
203
+ if headers:
204
+ self.headers.update(headers)
205
+ user_agent = data.get("user_agent") or data.get("userAgent")
206
+ if user_agent:
207
+ self.headers["User-Agent"] = user_agent
208
+
209
+
210
+ def create_scraper(
211
+ sess=None,
212
+ api_key=None,
213
+ proxy=None,
214
+ captcha=None,
215
+ browser=None,
216
+ delay=None,
217
+ interpreter=None,
218
+ debug=False,
219
+ max_solve_attempts=3,
220
+ **kwargs,
221
+ ):
222
+ """Create a :class:`CloudScraper`, mirroring ``cloudscraper.create_scraper``.
223
+
224
+ All of cloudscraper's real kwargs are accepted (``browser``, ``delay``,
225
+ ``interpreter``, ``captcha``, ``sess``, ``allow_brotli`` via ``**kwargs``)
226
+ and unknown kwargs never raise, so this is a true drop-in.
227
+
228
+ The Peak API key is resolved with precedence
229
+ explicit ``api_key`` > ``captcha`` dict > ``PEAK_API_KEY`` env.
230
+ """
231
+ resolved_key = resolve_api_key(api_key, captcha)
232
+ scraper = CloudScraper(
233
+ api_key=resolved_key,
234
+ proxy=proxy,
235
+ max_solve_attempts=max_solve_attempts,
236
+ debug=debug,
237
+ browser=browser,
238
+ delay=delay,
239
+ interpreter=interpreter,
240
+ **kwargs,
241
+ )
242
+ if sess is not None:
243
+ _adopt_session(scraper, sess)
244
+ return scraper
245
+
246
+
247
+ def _adopt_session(scraper: CloudScraper, sess) -> None:
248
+ """Carry state over from an existing requests.Session, like cloudscraper."""
249
+ for attr in ("headers", "proxies", "params", "cookies"):
250
+ value = getattr(sess, attr, None)
251
+ if value:
252
+ getattr(scraper, attr).update(value)
253
+ for attr in ("auth", "cert", "verify", "trust_env", "max_redirects"):
254
+ value = getattr(sess, attr, None)
255
+ if value is not None:
256
+ setattr(scraper, attr, value)
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.5
2
+ Name: cloudscraper-turnstile
3
+ Version: 0.1.0
4
+ Summary: cloudscraper drop-in that actually solves Cloudflare Turnstile and the 5s interstitial via the Peak API. Subclasses requests.Session; swap two lines and your existing scraper works.
5
+ Project-URL: Homepage, https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile
6
+ Project-URL: Documentation, https://peak.fo/docs/turnstile?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile
7
+ Project-URL: Pricing, https://peak.fo/pricing?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile
8
+ Project-URL: Source, https://github.com/CircuitSavage/cloudscraper-turnstile
9
+ Author: Peak
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: 403,anti-bot,bypass,captcha,captcha-solver,cloudflare,cloudflare-bypass,cloudflare-turnstile,cloudscraper,cloudscraper-alternative,requests,scraper,turnstile,web-scraping
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Internet :: WWW/HTTP
25
+ Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Requires-Python: >=3.8
28
+ Requires-Dist: requests>=2.25
29
+ Description-Content-Type: text/markdown
30
+
31
+ <a href="https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile">
32
+ <img src="https://raw.githubusercontent.com/CircuitSavage/cloudscraper-turnstile/main/assets/peak-banner.png" alt="Peak — solve Cloudflare Turnstile & the 5s challenge in ~1s" width="100%">
33
+ </a>
34
+
35
+ # cloudscraper-turnstile
36
+
37
+ **cloudscraper-turnstile** is a drop-in replacement for [cloudscraper](https://github.com/VeNoMouS/cloudscraper) that actually solves Cloudflare Turnstile and the 5s "Just a moment..." interstitial. It subclasses `requests.Session` exactly like cloudscraper does, so you change one import line and your existing scraper keeps working, except now the requests that used to return `403` come back with the real page.
38
+
39
+ ```python
40
+ import cloudscraper_turnstile as cloudscraper
41
+
42
+ scraper = cloudscraper.create_scraper(api_key="pk_your_api_key")
43
+ resp = scraper.get("https://protected.example.com/") # Turnstile solved, real page returned
44
+ ```
45
+
46
+ ## Why cloudscraper can't do this anymore
47
+
48
+ cloudscraper is a good tool for the challenge it was built for, but that challenge is mostly gone:
49
+
50
+ - **It only ever solved the legacy IUAM challenge.** cloudscraper works by reading Cloudflare's old "I'm Under Attack Mode" page, extracting the JavaScript math problem, and evaluating it. That is the entire mechanism.
51
+ - **It has no JS engine and no browser.** Modern Cloudflare managed challenges and Turnstile run real, obfuscated browser JavaScript and collect behavioral and fingerprint signals. There is nothing in the page for a regex-and-eval tool to solve, so the request stays on the challenge page and you get a `403`, a `503`, or an endless "Just a moment..." loop.
52
+ - **Its own "Turnstile support" is a hand-off.** cloudscraper never solved Turnstile itself. It added hooks to pass the challenge to a third-party paid CAPTCHA API and inject the returned token. Without one of those API keys configured, Turnstile support does nothing.
53
+ - **The project is effectively unmaintained.** Its last real release was in 2023. Cloudflare has shipped many detection changes since.
54
+
55
+ So on any site that switched to Turnstile or the managed 5s challenge (most of them, by now), plain cloudscraper returns the challenge HTML instead of your data. This package fills exactly that gap: it keeps cloudscraper's `create_scraper` / `requests.Session` shape and does the one thing cloudscraper cannot, by sending the challenge to a solver that runs a real browser.
56
+
57
+ ## Powered by Peak
58
+
59
+ This package uses [Peak](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile) to solve Turnstile and the 5s challenge.
60
+
61
+ - Solve Cloudflare Turnstile & the 5s challenge in about a second
62
+ - Pay only for successful solves, from $1 / 1,000
63
+ - 1,000 free solves to start, no card.
64
+
65
+ → [Get your free API key](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile) · [Docs](https://peak.fo/docs/turnstile?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile) · [Pricing](https://peak.fo/pricing?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile)
66
+
67
+ ## Install
68
+
69
+ ```bash
70
+ pip install cloudscraper-turnstile
71
+ ```
72
+
73
+ The only dependency is `requests` (you already have it if you used cloudscraper).
74
+
75
+ ## Migration guide
76
+
77
+ There is no rewrite. cloudscraper-turnstile mirrors cloudscraper's public API: `create_scraper(...)` returns a `CloudScraper` object that subclasses `requests.Session`, so `.get`, `.post`, `.request`, `.cookies`, and `.headers` all behave the same.
78
+
79
+ **Before**
80
+
81
+ ```python
82
+ import cloudscraper
83
+
84
+ scraper = cloudscraper.create_scraper()
85
+ resp = scraper.get("https://protected.example.com/") # 403 / "Just a moment..." on Turnstile sites
86
+ ```
87
+
88
+ **After**
89
+
90
+ ```python
91
+ import cloudscraper_turnstile as cloudscraper # the only line that changes
92
+
93
+ scraper = cloudscraper.create_scraper() # reads PEAK_API_KEY from env
94
+ resp = scraper.get("https://protected.example.com/") # Turnstile solved, real page returned
95
+ ```
96
+
97
+ If you were already using cloudscraper's captcha-provider style, that keeps working too, so migration is a no-op:
98
+
99
+ ```python
100
+ scraper = cloudscraper.create_scraper(
101
+ captcha={"provider": "peak", "api_key": "pk_your_api_key"},
102
+ )
103
+ ```
104
+
105
+ Existing cloudscraper kwargs (`browser`, `delay`, `interpreter`, `allow_brotli`, `sess`, ...) are accepted and never raise, so you do not have to touch the rest of your `create_scraper` call.
106
+
107
+ ## Quickstart
108
+
109
+ ```bash
110
+ pip install cloudscraper-turnstile requests
111
+ export PEAK_API_KEY=pk_your_api_key # Windows: setx PEAK_API_KEY pk_your_api_key
112
+ ```
113
+
114
+ ```python
115
+ import os
116
+ import cloudscraper_turnstile as cloudscraper
117
+
118
+ scraper = cloudscraper.create_scraper(api_key=os.environ["PEAK_API_KEY"])
119
+
120
+ # Use it exactly like requests / cloudscraper. A Turnstile or 5s challenge is
121
+ # detected, solved through Peak, and the request is retried transparently.
122
+ resp = scraper.get("https://protected.example.com/")
123
+ print(resp.status_code) # 200
124
+ print(resp.text) # the real page, not the challenge
125
+
126
+ # Cookies obtained during the solve (including cf_clearance) persist on the
127
+ # session for every later request.
128
+ resp2 = scraper.post(
129
+ "https://protected.example.com/api/search",
130
+ json={"q": "widgets"},
131
+ )
132
+ ```
133
+
134
+ ### Where the key comes from
135
+
136
+ The API key is resolved in this order:
137
+
138
+ 1. Explicit `create_scraper(api_key="pk_...")`
139
+ 2. `create_scraper(captcha={"provider": "peak", "api_key": "pk_..."})`
140
+ 3. `PEAK_API_KEY` environment variable
141
+
142
+ ### Using a proxy
143
+
144
+ Pass a proxy and it is forwarded to Peak, so the solve happens from the same IP as your crawl (this matters, since Cloudflare ties clearance to the requesting IP):
145
+
146
+ ```python
147
+ scraper = cloudscraper.create_scraper(
148
+ api_key="pk_your_api_key",
149
+ proxy="http://user:pass@ip:port",
150
+ )
151
+ ```
152
+
153
+ If you set `scraper.proxies` the requests way instead, that proxy is used for the solve automatically.
154
+
155
+ ## Compatibility
156
+
157
+ | cloudscraper API | Status in cloudscraper-turnstile |
158
+ | --- | --- |
159
+ | `create_scraper(**kwargs)` | Supported. Returns a `requests.Session` subclass. |
160
+ | Returns a `requests.Session` | Yes. `CloudScraper(requests.Session)`. |
161
+ | `.get / .post / .put / .delete / .request` | Supported (inherited from `requests.Session`). |
162
+ | `.cookies`, `.headers`, `.proxies`, `.auth` | Supported (session state persists across the solve retry). |
163
+ | `sess=` (adopt an existing Session) | Supported (cookies, headers, proxies, auth carried over). |
164
+ | `captcha={"provider": ..., "api_key": ...}` | Supported. `provider: "peak"` is native; the `api_key` is read regardless. |
165
+ | `browser=`, `delay=`, `interpreter=`, `allow_brotli=`, `debug=` | Accepted, never raise. `debug=True` prints solve steps. |
166
+ | Legacy IUAM JS-math challenge | Handled by Cloudflare's own retry path; not the focus. |
167
+ | Cloudflare Turnstile | **Solved** via Peak (`turnstiletask`). |
168
+ | Cloudflare 5s "Just a moment" / managed | **Solved** via Peak (`cloudflare5stask`). |
169
+
170
+ ## cloudscraper vs cloudscraper-turnstile
171
+
172
+ | Challenge / trait | cloudscraper | cloudscraper-turnstile |
173
+ | --- | --- | --- |
174
+ | Legacy IUAM JS-math | Yes | Yes |
175
+ | Cloudflare Turnstile | No (hands off to a paid API you must wire up) | **Yes** |
176
+ | 5s "Just a moment" interstitial | No (no JS engine) | **Yes** |
177
+ | Managed challenge | No | **Yes** |
178
+ | `requests.Session` drop-in | Yes | Yes |
179
+ | Actively maintained | No (last release 2023) | Yes |
180
+
181
+ ## FAQ
182
+
183
+ **Why is cloudscraper not working in 2026?**
184
+ Because the site moved to Cloudflare Turnstile or the managed 5s challenge. cloudscraper only solves the old IUAM JavaScript-math page and has no JS engine, so on a modern challenge it returns the challenge HTML (usually `403`, `503`, or a "Just a moment..." page) instead of your data. Its last release was in 2023. cloudscraper-turnstile detects those challenges and solves them through Peak.
185
+
186
+ **What is a good cloudscraper alternative for Turnstile?**
187
+ cloudscraper-turnstile is built to be that alternative: same `create_scraper` API, same `requests.Session` object, but it actually solves Turnstile. Change the import, add a Peak API key, and your existing code runs.
188
+
189
+ **How do I fix cloudscraper 403 Forbidden?**
190
+ A `403` from a Cloudflare-protected site usually means you received the challenge page, not a real block. Confirm the body contains `cf-turnstile`, `Just a moment`, or `cf_chl_opt`. If so, switch to `import cloudscraper_turnstile as cloudscraper`, set `PEAK_API_KEY`, and the challenge is solved and the request retried automatically. If the proxy/IP that gets challenged is not your default one, pass `proxy=` so the solve matches.
191
+
192
+ **Does cloudscraper solve Cloudflare Turnstile?**
193
+ Not on its own. cloudscraper never solved Turnstile itself; it only added hooks to pass the token from an external paid CAPTCHA service. cloudscraper-turnstile does the solve for you through Peak and injects the `cf-turnstile-response` token, so there is nothing else to wire up.
194
+
195
+ **Do I need a real browser or Selenium?**
196
+ No. This is a pure `requests`-based client. The browser work happens on Peak's side; you send the sitekey and URL and get a token (or a `cf_clearance` cookie for the 5s challenge) back.
197
+
198
+ **Does it handle the 5s "Just a moment" page too?**
199
+ Yes. When the response is the interstitial rather than a Turnstile widget, the package calls Peak's `cloudflare5stask`, sets the returned `cf_clearance` cookie (and user-agent) on the session, and re-requests the original URL.
200
+
201
+ **Will it loop forever if a solve fails?**
202
+ No. Solving is capped by `max_solve_attempts` (default 3). After that the last response is returned as-is so you can inspect it.
203
+
204
+ ## Legitimate use
205
+
206
+ Use this for automation, QA, monitoring, and scraping public data you are allowed to access. Respect each target's Terms of Service and `robots.txt`, rate-limit yourself, and do not use it for credential stuffing or to access data you have no right to. You are responsible for how you use it.
207
+
208
+ ## Links
209
+
210
+ - [Peak home](https://peak.fo/?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile)
211
+ - [Turnstile docs](https://peak.fo/docs/turnstile?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile)
212
+ - [Pricing](https://peak.fo/pricing?utm_source=github&utm_medium=readme&utm_campaign=packages&utm_content=cloudscraper-turnstile)
213
+
214
+ ## License
215
+
216
+ MIT. See [LICENSE](./LICENSE).
@@ -0,0 +1,8 @@
1
+ cloudscraper_turnstile/__init__.py,sha256=wVJk9iKTUSprVCZax8JuQgcENQnHaeVWY9xkbIF3TTo,1143
2
+ cloudscraper_turnstile/detect.py,sha256=uAQmuVNMPLwF9H5_OpoY_GL_pyB-zF734UHMIDF792Y,3955
3
+ cloudscraper_turnstile/peak.py,sha256=9CZrWgod6S0yI1ld5StycWHuFbFVDKUBqUZkrFav0pU,4921
4
+ cloudscraper_turnstile/scraper.py,sha256=psTHUYYR_F-SaakQMaJhK_3VWhqYMOGO3wrjFPiuzv4,10075
5
+ cloudscraper_turnstile-0.1.0.dist-info/METADATA,sha256=3wdqlwBNNEpbFCJW5U8XS1Hfeqj8pb-1ExE3IPj5_Mc,12284
6
+ cloudscraper_turnstile-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
7
+ cloudscraper_turnstile-0.1.0.dist-info/licenses/LICENSE,sha256=LAOHjw1ZMlJ4tBwxVtmcxNwMQ79ELPXKo0q8yQdGsJ4,1061
8
+ cloudscraper_turnstile-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peak
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.