I am trying to solve a recaptcha v2 with callback, the recaptcha is the picture solving. I’m not entirely sure what my issue is because I only get hit with the recaptcha when I am in headless mode.
I am successfully extracting the Callback and sending with the solve. When this happens, the webpage advances to the next page. But the captcha window is still open. I am struggling to click the “verify” button -I am trying various methods to switch to the iframe but the “verify” button is not found- whether I use xpath, CSS etc
Can anyone help figure out where I am going wrong with this?
def solve_recaptcha(api_key, site_key, url):
print(f"Sending sitekey to 2Captcha: {site_key}")
# Send the sitekey to 2Captcha for solving
response = requests.post(
'http://2captcha.com/in.php',
data={
'key': api_key,
'method': 'userrecaptcha',
'googlekey': site_key,
'pageurl': url
}
)
print(f"2Captcha response: {response.text}")
if response.text.startswith('OK|'):
captcha_id = response.text.split('|')[1]
else:
raise Exception(f"Error from 2Captcha: {response.text}")
# Retrieve the CAPTCHA solution
while True:
time.sleep(5)
result = requests.get(f'http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}')
if result.text == 'CAPCHA_NOT_READY':
continue
if result.text.startswith('OK|'):
captcha_solution = result.text.split('|')[1]
break
else:
raise Exception(f"Error from 2Captcha: {result.text}")
print(f"CAPTCHA Solution: {captcha_solution}")
return captcha_solution
try:
# JavaScript function to find reCAPTCHA clients
find_recaptcha_clients_js = """
function findRecaptchaClients() {
if (typeof (___grecaptcha_cfg) !== 'undefined') {
return Object.entries(___grecaptcha_cfg.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();
"""
# Execute the JavaScript function to get reCAPTCHA clients data
recaptcha_data = driver.execute_script(find_recaptcha_clients_js)
print(f"reCAPTCHA Data: {recaptcha_data}")
if recaptcha_data:
# Assuming the first reCAPTCHA client found is the target
recaptcha_info = recaptcha_data[0]
site_key = recaptcha_info['sitekey']
callback_function = recaptcha_info.get('callback')
# Solve the reCAPTCHA
captcha_solution = solve_recaptcha(api_key, site_key, url)
# Inject the solved token into the page
driver.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML='{captcha_solution}';")
# Execute the callback function if it exists
if callback_function:
driver.execute_script(f"var callback = {callback_function}; callback('{captcha_solution}');")
print("CAPTCHA solved and token submitted successfully.")
else:
print("No reCAPTCHA found on the page.")
except Exception as e:
print(f"Error: {e}")
I attaches some pics to show how the page is advancing after submitting solve [enter image description here](https://i.sstatic.net/TpprM7PJ.png)
As you can see, the page advances after submitting the solve, but iframe containing captcha is still present
Switching to iframe with
driver.switch_to.frame(0)
wait = WebDriverWait(driver, 10)
button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[id*='verify']")))
# Click the button
button.click()
print("Button clicked successfully!")
Bob is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.