-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathasync_solver.py
178 lines (149 loc) · 6.48 KB
/
async_solver.py
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
import asyncio
import time
from typing import Dict, Optional
from dataclasses import dataclass
from patchright.async_api import async_playwright, Page, BrowserContext
from logmagix import Logger, Loader
@dataclass
class TurnstileResult:
turnstile_value: Optional[str]
elapsed_time_seconds: float
status: str
reason: Optional[str] = None
class AsyncTurnstileSolver:
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Turnstile Solver</title>
<script
src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=onloadTurnstileCallback"
async=""
defer=""
></script>
</head>
<body>
<!-- cf turnstile -->
</body>
</html>
"""
def __init__(self, debug: bool = False):
self.debug = debug
self.log = Logger()
self.loader = Loader(desc="Solving captcha...", timeout=0.05)
self.browser_args = [
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-background-networking",
"--disable-background-timer-throttling",
"--disable-backgrounding-occluded-windows",
"--disable-renderer-backgrounding",
"--window-position=2000,2000",
]
async def _setup_page(self, context: BrowserContext, url: str, sitekey: str) -> Page:
"""Set up the page with Turnstile widget."""
page = await context.new_page()
url_with_slash = url + "/" if not url.endswith("/") else url
if self.debug:
self.log.debug(f"Navigating to URL: {url_with_slash}")
turnstile_div = f'<div class="cf-turnstile" data-sitekey="{sitekey}"></div>'
page_data = self.HTML_TEMPLATE.replace("<!-- cf turnstile -->", turnstile_div)
await page.route(url_with_slash, lambda route: route.fulfill(body=page_data, status=200))
await page.goto(url_with_slash)
if self.debug:
self.log.debug("Getting window dimensions.")
page.window_width = await page.evaluate("window.innerWidth")
page.window_height = await page.evaluate("window.innerHeight")
return page
async def _get_turnstile_response(self, page: Page, max_attempts: int = 10) -> Optional[str]:
"""Attempt to retrieve Turnstile response."""
attempts = 0
if self.debug:
self.log.debug("Starting Turnstile response retrieval loop.")
while attempts < max_attempts:
turnstile_check = await page.eval_on_selector(
"[name=cf-turnstile-response]",
"el => el.value"
)
if turnstile_check == "":
if self.debug:
self.log.debug(f"Attempt {attempts + 1}: No Turnstile response yet.")
await page.evaluate("document.querySelector('.cf-turnstile').style.width = '70px'")
await page.click(".cf-turnstile")
await asyncio.sleep(0.5)
attempts += 1
else:
turnstile_element = await page.query_selector("[name=cf-turnstile-response]")
if turnstile_element:
value = await turnstile_element.get_attribute("value")
if self.debug:
self.log.debug(f"Turnstile response received: {value}")
return value
break
return None
async def solve(self, url: str, sitekey: str, headless: bool = False) -> TurnstileResult:
"""
Solve the Turnstile challenge and return the result.
Args:
url: The URL where the Turnstile challenge is hosted
sitekey: The Turnstile sitekey
headless: Whether to run the browser in headless mode
Returns:
TurnstileResult object containing the solution details
"""
self.loader.start()
start_time = time.time()
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=headless, args=self.browser_args)
context = await browser.new_context()
try:
page = await self._setup_page(context, url, sitekey)
turnstile_value = await self._get_turnstile_response(page)
elapsed_time = round(time.time() - start_time, 3)
if not turnstile_value:
result = TurnstileResult(
turnstile_value=None,
elapsed_time_seconds=elapsed_time,
status="failure",
reason="Max attempts reached without token retrieval"
)
self.log.failure("Failed to retrieve Turnstile value.")
else:
result = TurnstileResult(
turnstile_value=turnstile_value,
elapsed_time_seconds=elapsed_time,
status="success"
)
self.log.message(
"Cloudflare",
f"Successfully solved captcha: {turnstile_value[:45]}...",
start=start_time,
end=time.time()
)
finally:
await context.close()
await browser.close()
self.loader.stop()
if self.debug:
self.log.debug(f"Elapsed time: {result.elapsed_time_seconds} seconds")
self.log.debug("Browser closed. Returning result.")
return result
async def get_turnstile_token(headless: bool = False, url: str = None, sitekey: str = None) -> Dict:
"""Legacy wrapper function for backward compatibility."""
solver = AsyncTurnstileSolver()
result = await solver.solve(url=url, sitekey=sitekey, headless=headless)
return result.__dict__
if __name__ == "__main__":
async def main():
result = await get_turnstile_token(
headless=False,
url="https://bypass.city/",
sitekey="0x4AAAAAAAGzw6rXeQWJ_y2P"
)
print(result)
asyncio.run(main())
# Credits for the changes: github.com/sexfrance
# Credit for the original script: github.com/Theyka