-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathrecaptcha_v2_callback_variant2.py
More file actions
207 lines (166 loc) · 6.57 KB
/
recaptcha_v2_callback_variant2.py
File metadata and controls
207 lines (166 loc) · 6.57 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
import os
import time
from seleniumbase import Driver
from selenium.common.exceptions import JavascriptException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from twocaptcha import TwoCaptcha
# Description:
# Captcha parameters are determined automatically with the help of JavaScript script executed on the page.
# CONFIGURATION
url = "https://2captcha.com/demo/recaptcha-v2-callback"
apikey = os.getenv("APIKEY_2CAPTCHA")
# JavaScript script to find reCAPTCHA clients and extract sitekey and callback function
script = """
function findRecaptchaClients() {
// eslint-disable-next-line camelcase
if (typeof (___grecaptcha_cfg) !== 'undefined') {
const clients = ___grecaptcha_cfg.clients || {};
// eslint-disable-next-line camelcase, no-undef
return Object.entries(clients).map(([cid, client]) => {
const data = { id: cid, version: cid >= 10000 ? 'V3' : 'V2' };
const objects = Object.entries(client).filter(([_, value]) => value && typeof value === 'object');
objects.forEach(([toplevelKey, toplevel]) => {
const found = Object.entries(toplevel).find(([_, value]) => (
value && typeof value === 'object' && 'sitekey' in value && 'size' in value
));
if (typeof toplevel === 'object' && toplevel instanceof HTMLElement && toplevel['tagName'] === 'DIV'){
data.pageurl = toplevel.baseURI;
}
if (found) {
const [sublevelKey, sublevel] = found;
data.sitekey = sublevel.sitekey;
const callbackKey = data.version === 'V2' ? 'callback' : 'promise-callback';
const callback = sublevel[callbackKey];
if (!callback) {
data.callback = null;
data.function = null;
} else {
data.function = callback;
const keys = [cid, toplevelKey, sublevelKey, callbackKey].map((key) => `['${key}']`).join('');
data.callback = `___grecaptcha_cfg.clients${keys}`;
}
}
});
return data;
});
}
return [];
}
return findRecaptchaClients()
"""
# LOCATORS
success_message_locator = "//p[contains(@class,'successMessage')]"
# GETTERS
def get_element(browser, locator):
"""
Waits for an element to be clickable and returns it.
This helper can be copied and reused in other projects that use SeleniumBase.
"""
return WebDriverWait(browser, 30).until(EC.element_to_be_clickable((By.XPATH, locator)))
# ACTIONS
def get_captcha_params(browser, script):
"""
Executes the given JavaScript script to extract the captcha callback function name and sitekey.
Args:
script (str): The JavaScript script to execute.
Returns:
tuple: A tuple containing the callback function name and the sitekey.
"""
WebDriverWait(browser, 30).until(
lambda driver: driver.execute_script("""
return Boolean(
window.___grecaptcha_cfg &&
___grecaptcha_cfg.clients &&
Object.keys(___grecaptcha_cfg.clients).length
);
""")
)
retries = 0
while retries < 3:
try:
result = browser.execute_script(script)
if not result:
raise IndexError("reCAPTCHA clients list is empty")
captcha_data = next(
(
item for item in result
if item and item.get("sitekey") and item.get("function")
),
None,
)
if not captcha_data:
raise IndexError("Callback function or sitekey is not ready yet")
callback_function_name = captcha_data['function']
sitekey = captcha_data['sitekey']
print("Got the callback function name and site key")
return callback_function_name, sitekey
except (IndexError, KeyError, TypeError, JavascriptException):
retries += 1
time.sleep(1) # Wait a bit before retrying
raise TimeoutException("Timed out waiting for reCAPTCHA callback and sitekey")
def solver_captcha(apikey, sitekey, url):
"""
Solves the reCaptcha using the 2Captcha service.
Args:
apikey (str): The 2Captcha API key.
sitekey (str): The sitekey for the captcha.
url (str): The URL where the captcha is located.
Returns:
str: The solved captcha code.
"""
solver = TwoCaptcha(apikey)
try:
result = solver.recaptcha(sitekey=sitekey, url=url)
print(f"Captcha solved")
return result['code']
except Exception as e:
print(f"An error occurred: {e}")
return None
def send_token_callback(browser, callback_function, token):
"""
Executes the callback function with the given token.
Args:
callback_function (str): The name of the callback function.
token (str): The solved captcha token.
"""
script = f"{callback_function}('{token}')"
browser.execute_script(script)
print("The token is sent to the callback function")
def final_message(browser, locator):
"""
Retrieves and prints the final success message.
Args:
locator (str): The XPath locator of the success message.
"""
message = get_element(browser, locator).text
print(message)
def main():
"""
Runs the demo flow for solving reCaptcha v2 with a callback using
automatic extraction of callback and sitekey.
Helper functions (`get_captcha_params`, `solver_captcha`, `send_token_callback`, etc.)
are designed so they can be copied and reused independently.
"""
if not apikey:
raise RuntimeError("Set APIKEY_2CAPTCHA environment variable")
with Driver(browser="chrome", headless=False) as browser:
browser.get(url)
print("Started")
# Extracting callback function name and sitekey using the provided script
callback_function, sitekey = get_captcha_params(browser, script)
# Solving the captcha and receiving the token
token = solver_captcha(apikey, sitekey, url)
if token:
# Sending the solved captcha token to the callback function
send_token_callback(browser, callback_function, token)
# Retrieving and printing the final success message
final_message(browser, success_message_locator)
# Explicit pause to observe the result
time.sleep(5)
print("Finished")
else:
print("Failed to solve captcha")
if __name__ == "__main__":
main()