Guías
Clic en imágenes de hCaptcha con Selenium
Esta página se tradujo automáticamente de la versión en chino y puede contener errores. Prevalece la versión en chino.
Este tutorial abre la página de demostración de hCaptcha con Selenium 4 y resuelve la cuadrícula 3×3 en un navegador real: lee la pregunta y las 9 imágenes, consulta a reconocimiento de imágenes de hCaptcha (HCaptchaClassification) cuáles son el objetivo y simula los clics.
hCaptcha también tiene preguntas de hacer clic en una posición y de arrastrar, que devuelven coordenadas en lugar de celdas; consulta reconocimiento de imágenes de hCaptcha. Si no quieres escribir código, la extensión del navegador las resuelve todas.
Preparación
Sección titulada «Preparación»pip install requests seleniumexport YESCAPTCHA_CLIENT_KEY=your_client_key- Haz clic en la casilla. Está dentro del iframe de hCaptcha cuya URL contiene
frame=checkbox; cambia a ese iframe y haz clic en#checkbox. - Cambia al iframe de la pregunta. Su URL contiene
frame=challenge. - Lee la pregunta. El texto de
.prompt-textes la pregunta; envíala tal cual a la API (se recomienda cambiar el idioma de la interfaz de hCaptcha a inglés o chino simplificado). Si junto a la pregunta aparecen imágenes de ejemplo, inclúyelas también enanchors. - Obtén las imágenes. La imagen de fondo de
.task-image .imagede cada celda es una imagen; descárgalas en orden, conviértelas a Base64 y arma la listaqueries. - Reconoce. Llama a
createTaskcon el tipoHCaptchaClassification. Los elementos deobjectscorresponden uno a uno con las celdas;trueindica que es objetivo. - Haz clic y envía. Haz clic en las celdas objetivo y pulsa el botón de enviar. Pueden seguir varias rondas; repite los pasos 3 a 6.
- Listo. Tras pasar la verificación, el campo
h-captcha-responsede la página contiene el token, que se envía junto con el formulario.
Código completo
Sección titulada «Código completo»"""Click through an hCaptcha 3x3 image challenge with Selenium 4 and HCaptchaClassification.
Flow: open the page -> click the checkbox -> read the question and the 9 images ->ask YesCaptcha which images match -> click them -> submit. Repeat while new rounds appear.
Run: pip install requests selenium export YESCAPTCHA_CLIENT_KEY=your_client_key python hcaptcha_click_selenium.pyEach recognized round is charged (see the price list; rounds with no target found are free).hCaptcha changes its page structure often; adjust the selectors below if a step stops working.Click and drag questions return coordinates instead; see the HCaptchaClassification page."""import base64import osimport reimport time
import requestsfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.support.wait import WebDriverWait
CLIENT_KEY = os.environ["YESCAPTCHA_CLIENT_KEY"]PAGE_URL = "https://accounts.hcaptcha.com/demo"
def classify(question, images_b64): task = {"type": "HCaptchaClassification", "question": question, "queries": images_b64} data = requests.post( "https://api.yescaptcha.com/createTask", json={"clientKey": CLIENT_KEY, "task": task}, timeout=60, ).json() if data.get("errorId"): raise RuntimeError(f"{data.get('errorCode')}: {data.get('errorDescription')}") return data["solution"] # synchronous
def background_image_b64(element): """The tiles are <div>s with a CSS background image; download it and Base64-encode it.""" style = element.get_attribute("style") or "" match = re.search(r'url\("?(.*?)"?\)', style) if not match: return None return base64.b64encode(requests.get(match.group(1), timeout=30).content).decode()
driver = webdriver.Chrome()wait = WebDriverWait(driver, 15)try: driver.get(PAGE_URL)
# 1. Click the checkbox (inside the first hCaptcha iframe) wait.until(EC.frame_to_be_available_and_switch_to_it( (By.CSS_SELECTOR, 'iframe[src*="hcaptcha"][src*="frame=checkbox"]'))) wait.until(EC.element_to_be_clickable((By.ID, "checkbox"))).click() driver.switch_to.default_content()
# 2. Solve rounds in the challenge iframe wait.until(EC.frame_to_be_available_and_switch_to_it( (By.CSS_SELECTOR, 'iframe[src*="hcaptcha"][src*="frame=challenge"]'))) for _ in range(5): question = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".prompt-text"))).text.strip() tiles = driver.find_elements(By.CSS_SELECTOR, ".task-image") images = [background_image_b64(t.find_element(By.CSS_SELECTOR, ".image")) for t in tiles] if not tiles or None in images: print("not a 3x3 image challenge; see the docs for click/drag questions") break solution = classify(question, images) for tile, hit in zip(tiles, solution.get("objects", [])): if hit: tile.click() time.sleep(0.3) driver.find_element(By.CSS_SELECTOR, ".button-submit").click() time.sleep(3) if not driver.find_elements(By.CSS_SELECTOR, ".task-image"): break
driver.switch_to.default_content() token = driver.find_element(By.NAME, "h-captcha-response").get_attribute("value") print("token received" if token else "not passed")finally: driver.quit()- hCaptcha cambia a menudo la estructura de su página; si los selectores del código dejan de funcionar, ajústalos según la página real.
- Cada ronda reconocida implica un cobro de puntos; las rondas en las que no se encuentra ningún objetivo no se cobran. Si la verificación falla tras los clics, puedes reportarlo en el plazo de 1 hora para solicitar un reembolso tras reportar.
- Si una pregunta nueva devuelve
ERROR_UNKNOWN_QUESTION, actualiza para obtener otra o contacta con soporte.
© YesCaptcha