-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcloudflare_challenge_page.py
192 lines (156 loc) · 6.45 KB
/
cloudflare_challenge_page.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import os
import time
import json
import re
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from twocaptcha import TwoCaptcha
# CONFIGURATION
url = "https://2captcha.com/demo/cloudflare-turnstile-challenge"
apikey = os.getenv('APIKEY_2CAPTCHA')
solver = TwoCaptcha(apikey)
"""
When a web page first loads, some JavaScript functions and objects (such as window.turnstile) may already be initialized
and executed. If the interception script is launched too late, this may lead to the fact that the necessary parameters
will already be lost, or the script simply will not have time to intercept the right moment. Refreshing the page ensures
that everything starts from scratch and you trigger the interception at the right time.
"""
intercept_script = """
console.clear = () => console.log('Console was cleared')
const i = setInterval(()=>{
if (window.turnstile)
console.log('success!!')
{clearInterval(i)
window.turnstile.render = (a,b) => {
let params = {
sitekey: b.sitekey,
pageurl: window.location.href,
data: b.cData,
pagedata: b.chlPageData,
action: b.action,
userAgent: navigator.userAgent,
}
console.log('intercepted-params:' + JSON.stringify(params))
window.cfCallback = b.callback
return }
}
},50)
"""
# LOCATORS
success_message_locator = "//p[contains(@class,'successMessage')]"
# GETTERS
def get_present_element(locator):
"""Waits for an element to be present and returns it"""
return WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, locator)))
# ACTIONS
def get_captcha_params(script):
"""
Refreshes the page, injects a JavaScript script to intercept Turnstile parameters, and retrieves them.
Args:
script (str): The JavaScript code to be injected.
Returns:
dict: The intercepted Turnstile parameters as a dictionary.
"""
browser.refresh() # Refresh the page to ensure the script is applied correctly
browser.execute_script(script) # Inject the interception script
time.sleep(5) # Allow some time for the script to execute
logs = browser.get_log("browser") # Retrieve the browser logs
params = None
for log in logs:
if "intercepted-params:" in log['message']:
log_entry = log['message'].encode('utf-8').decode('unicode_escape')
match = re.search(r'intercepted-params:({.*?})', log_entry)
if match:
json_string = match.group(1)
params = json.loads(json_string)
break
print("Parameters received")
return params
def solver_captcha(params):
"""
Solves the Turnstile captcha using the 2Captcha service.
Args:
params (dict): The intercepted Turnstile parameters.
Returns:
dict: The captcha id and the solved captcha code.
"""
try:
result = solver.turnstile(sitekey=params["sitekey"],
url=params["pageurl"],
action=params["action"],
data=params["data"],
pagedata=params["pagedata"],
useragent=params["userAgent"])
print(f"Captcha solved. Token: {result['code']}.")
return result
except Exception as e:
print(f"An error occurred: {e}")
return None
def send_token_callback(token):
"""
Executes the callback function with the given token.
Args:
token (str): The solved captcha token.
"""
script = f"cfCallback('{token}')"
browser.execute_script(script)
print("The token is sent to the callback function")
def final_message_and_report(locator, id):
"""
Retrieves and prints the final success message and sends a report to 2Captcha.
Submitting answer reports is not necessary to solve the captcha. But it can help you reduce the cost of the solution
and improve accuracy. We have described why it is important to submit reports in our blog:
https://2captcha.com/ru/blog/reportgood-reportbad
We recommend reporting both incorrect and correct answers.
Args:
locator (str): The XPath locator of the success message.
id (str): The captcha id for reporting.
"""
try:
# Check for success message
message = get_present_element(locator).text
print(message)
is_success = True
except TimeoutException:
# If the element is not found within the timeout
print("Timed out waiting for success message element")
is_success = False
except Exception as e:
# If another error occurs
print(f"Error retrieving final message: {e}")
is_success = False
# Send the report anyway
solver.report(id, is_success)
print(f"Report sent for id: {id}, success: {is_success}")
# MAIN LOGIC
chrome_options = Options()
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/126.0.0.0 Safari/537.36")
# Set logging preferences to capture only console logs
chrome_options.set_capability("goog:loggingPrefs", {"browser": "INFO"})
with webdriver.Chrome(service=Service(), options=chrome_options) as browser:
browser.get(url)
print("Started")
# Getting captcha params
params = get_captcha_params(intercept_script)
if params:
# Sent captcha to the solution in 2captcha API
result = solver_captcha(params)
if result:
# From the response from the service we get the captcha id and token
id, token = result['captchaId'], result['code']
# Applying the token on the page
send_token_callback(token)
# We check if there is a message about the successful solution of the captcha and send a report on the result
# using the captcha id
final_message_and_report(success_message_locator, id)
print("Finished")
else:
print("Failed to solve captcha")
else:
print("Failed to intercept parameters")