Python Selenium实现点击reCAPTCHA演示页复选框的代码求助
Fixing the reCAPTCHA Checkbox Click with Selenium
Got it, let's sort this out for you! The main issue you're hitting is that the reCAPTCHA checkbox lives inside an embedded iframe—so Selenium can't find it when searching the main page's DOM directly. Here's the complete, runnable code that handles the iframe switch and adds proper waits to avoid timing issues:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException try: # Initialize Firefox driver driver1 = webdriver.Firefox() driver1.get("https://www.google.com/recaptcha/api2/demo") # Wait for the reCAPTCHA iframe to load and switch to it # The iframe is identified by its src containing "recaptcha/api2/anchor" recaptcha_iframe = WebDriverWait(driver1, 10).until( EC.presence_of_element_located((By.XPATH, "//iframe[contains(@src, 'recaptcha/api2/anchor')]")) ) driver1.switch_to.frame(recaptcha_iframe) # Wait for the checkbox to be clickable, then click it recaptcha_checkbox = WebDriverWait(driver1, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, "recaptcha-checkbox-checkmark")) ) recaptcha_checkbox.click() # Optional: Switch back to the main page if you need to interact with other elements later # driver1.switch_to.default_content() except TimeoutException: print("Timed out waiting for reCAPTCHA elements to load") finally: # Keep the browser open for testing, or uncomment to close automatically # driver1.quit() pass
Key Details Explained:
- Switching to the iframe: The reCAPTCHA checkbox isn't part of the main page's HTML—it's loaded in a separate iframe. We use
switch_to.frame()to tell Selenium to look inside that iframe's DOM. - Explicit waits: Instead of using unreliable
time.sleep(), we useWebDriverWaitto wait until elements are present/clickable. This ensures the code doesn't try to interact with elements before they're fully loaded. - Element selection: The checkbox is targeted using its class name
recaptcha-checkbox-checkmark—this is a consistent selector for the standard reCAPTCHA checkbox.
内容的提问来源于stack exchange,提问作者omersk
相关产品推荐
相关产品推荐

