-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathrecaptcha_v3_extended_js_script.py
More file actions
216 lines (170 loc) · 6.01 KB
/
recaptcha_v3_extended_js_script.py
File metadata and controls
216 lines (170 loc) · 6.01 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
import os
import time
from seleniumbase import Driver
from selenium.common.exceptions import 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
# CONFIGURATION
url = "https://2captcha.com/demo/recaptcha-v3"
apikey = os.getenv("APIKEY_2CAPTCHA")
script = """
function findRecaptchaData() {
const results = [];
const sitekeyRegex = /^6[0-9A-Za-z_-]{20,}$/;
const actionRegex = /^[A-Za-z0-9_-]+$/;
// Collect the text of all scripts on the page.
const scriptContents = Array.from(document.scripts)
.map(script => script.innerHTML || '')
.join('\\n');
// Search for sitekey and action in multiple patterns.
const sitekeyPattern = /['"]sitekey['"]\\s*:\\s*['"]([^'"]+)['"]/gi;
const actionPattern = /['"]action['"]\\s*:\\s*['"]([^'"]+)['"]/gi;
const executePattern = /grecaptcha\\.execute\\s*\\(\\s*['"]([^'"]+)['"]\\s*,\\s*\\{[^}]*?\\baction\\b\\s*:\\s*['"]([^'"]+)['"][^}]*?\\}/gi;
let match;
while ((match = executePattern.exec(scriptContents)) !== null) {
if (sitekeyRegex.test(match[1]) && actionRegex.test(match[2])) {
results.push({
sitekey: match[1],
action: match[2]
});
}
}
const sitekeys = [];
while ((match = sitekeyPattern.exec(scriptContents)) !== null) {
sitekeys.push(match[1]);
}
const actions = [];
while ((match = actionPattern.exec(scriptContents)) !== null) {
actions.push(match[1]);
}
for (let i = 0; i < Math.min(sitekeys.length, actions.length); i++) {
if (sitekeyRegex.test(sitekeys[i]) && actionRegex.test(actions[i])) {
results.push({
sitekey: sitekeys[i],
action: actions[i]
});
}
}
return results;
}
return findRecaptchaData();
"""
# LOCATORS
submit_button_captcha_locator = "//button[@type='submit']"
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 JavaScript to get reCAPTCHA v3 parameters from the page.
Args:
browser: The SeleniumBase driver instance.
script (str): The JavaScript code to execute.
Returns:
tuple: The sitekey and action parameters.
"""
WebDriverWait(browser, 30).until(
lambda driver: driver.execute_script(
"return Array.from(document.scripts).some(script => (script.innerHTML || '').includes('grecaptcha'));"
)
)
retries = 0
while retries < 3:
result = browser.execute_script(script)
captcha_data = next(
(
item for item in result
if item and item.get("sitekey") and item.get("action")
),
None,
)
if captcha_data:
sitekey = captcha_data["sitekey"]
action = captcha_data["action"]
print("Parameters sitekey and action received")
return sitekey, action
retries += 1
time.sleep(1)
raise TimeoutException("Timed out waiting for reCAPTCHA v3 parameters")
def solver_captcha(apikey, sitekey, url, action):
"""
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.
action (str): The reCAPTCHA action value.
Returns:
str: The solved captcha code.
"""
solver = TwoCaptcha(apikey)
try:
result = solver.recaptcha(
sitekey=sitekey,
url=url,
action=action,
version="V3",
)
print("Captcha solved")
return result["code"]
except Exception as e:
print(f"An error occurred: {e}")
return None
def send_token(browser, token):
"""
Sends the solved reCAPTCHA token to the page.
Args:
browser: The SeleniumBase driver instance.
token (str): The solved captcha token.
"""
browser.execute_script(f"window.verifyRecaptcha('{token}')")
print("The token is sent")
def click_check_button(browser, locator):
"""
Clicks the captcha check button.
Args:
browser: The SeleniumBase driver instance.
locator (str): The XPath locator of the check button.
"""
get_element(browser, locator).click()
print("Pressed the Check button")
def final_message(browser, locator):
"""
Retrieves and prints the final success message.
Args:
browser: The SeleniumBase driver instance.
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 v3 using the extended JavaScript parser.
Helper functions (`get_captcha_params`, `solver_captcha`, `send_token`, 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")
sitekey, action = get_captcha_params(browser, script)
token = solver_captcha(apikey, sitekey, url, action)
if token:
send_token(browser, token)
click_check_button(browser, submit_button_captcha_locator)
final_message(browser, success_message_locator)
time.sleep(5)
print("Finished")
else:
print("Failed to solve captcha")
if __name__ == "__main__":
main()