Pular para o conteúdo
StatusPainel

Guias

Cliques em imagens do reCAPTCHA com Selenium

Esta página foi traduzida automaticamente da versão em chinês e pode conter erros. Prevalece a versão em chinês.

Este tutorial abre a página de demonstração do reCAPTCHA do Google com Selenium 4 e resolve o desafio de imagem em um navegador real: lê a pergunta e a imagem, pede ao reconhecimento de imagem do reCAPTCHA v2 (ReCaptchaV2Classification) quais quadrados clicar e simula os cliques. Em comparação com obter um token, a verificação é concluída no próprio navegador, o que ajuda em sites onde os tokens raramente passam.

Se preferir não escrever código, a extensão do navegador faz o mesmo usando a mesma API.

pip install requests selenium pillow
export YESCAPTCHA_CLIENT_KEY=your_client_key

O Chrome precisa estar instalado. O Selenium 4 baixa automaticamente o chromedriver compatível.

  1. Clique na caixa de seleção. Ela fica no iframe com title="reCAPTCHA"; mude para ele e clique em #recaptcha-anchor.
  2. Mude para o iframe do desafio. O desafio fica em outro iframe (cujo title contém “challenge”).
  3. Leia a pergunta. O texto em negrito em .rc-imageselect-desc-wrapper strong é o alvo, por exemplo “traffic lights”. A API pede o ID da pergunta, então converta o nome em ID (/m/015qff) usando a tabela de correspondência em IDs de pergunta. Com a interface do navegador em inglês, a correspondência fica mais fácil.
  4. Obtenha a imagem. Os quadrados são fatias de uma única imagem grande; baixe o src de td.rc-imageselect-tile img. Redimensione para 300×300 as imagens de 9 quadrados (3x3) e para 450×450 as de 16 quadrados (4x4), e converta para Base64.
  5. Reconheça. Chame createTask com o tipo ReCaptchaV2Classification, image e question. Ao adicionar "confidence": 0.5, as imagens 3x3 retornam todos os quadrados correspondentes de uma só vez, sem precisar tratar as imagens pequenas que aparecem depois do clique.
  6. Clique. objects lista os índices dos quadrados, a partir de 0, da esquerda para a direita e de cima para baixo; clique nos td correspondentes em sequência.
  7. Verifique. Clique em #recaptcha-verify-button. Se aparecer uma nova rodada, volte ao passo 3; quando a janela do desafio fechar, a verificação foi aprovada.
  8. Envie o formulário. Volte à página principal e clique no botão de envio.
recaptcha_click_selenium.py
"""Click through a reCAPTCHA v2 image challenge with Selenium 4 and ReCaptchaV2Classification.
Flow: open the page -> click the checkbox -> read the target name and the grid image ->
ask YesCaptcha which tiles to click -> click them -> press Verify. Repeat if a new challenge appears.
Run: pip install requests selenium pillow
export YESCAPTCHA_CLIENT_KEY=your_client_key
python recaptcha_click_selenium.py
Each recognized image is charged (see the price list). reCAPTCHA's page structure can change;
adjust the selectors below if a step stops working.
"""
import base64
import io
import os
import time
import requests
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
CLIENT_KEY = os.environ["YESCAPTCHA_CLIENT_KEY"]
PAGE_URL = "https://www.google.com/recaptcha/api2/demo"
# Target names shown in the challenge (English UI) -> question IDs.
# Full list: https://docs.yescaptcha.com/en/tasks/recaptcha-classification/
QUESTION_IDS = {
"taxis": "/m/0pg52", "bus": "/m/01bjv", "buses": "/m/01bjv", "motorcycles": "/m/04_sv",
"tractors": "/m/013xlm", "chimneys": "/m/01jk_4", "crosswalks": "/m/014xcs",
"traffic lights": "/m/015qff", "bicycles": "/m/0199g", "parking meters": "/m/015qbp",
"cars": "/m/0k4j", "bridges": "/m/015kr", "boats": "/m/019jd", "palm trees": "/m/0cdl1",
"mountains or hills": "/m/09d_r", "fire hydrants": "/m/01pns0", "a fire hydrant": "/m/01pns0",
"stairs": "/m/01lynh",
}
def classify(image_b64, question):
task = {"type": "ReCaptchaV2Classification", "image": image_b64, "question": question, "confidence": 0.5}
data = requests.post(
"https://api.yescaptcha.com/createTask",
json={"clientKey": CLIENT_KEY, "task": task},
timeout=30,
).json()
if data.get("errorId"):
raise RuntimeError(f"{data.get('errorCode')}: {data.get('errorDescription')}")
return data["solution"] # synchronous: the solution comes back right away
def grid_image_b64(url, size):
"""Download the challenge image and scale it to the standard size (300 for 3x3, 450 for 4x4)."""
img = Image.open(io.BytesIO(requests.get(url, timeout=30).content)).convert("RGB")
img = img.resize((size, size))
buf = io.BytesIO()
img.save(buf, format="JPEG")
return base64.b64encode(buf.getvalue()).decode()
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 15)
try:
driver.get(PAGE_URL)
# 1. Click the checkbox (inside the "reCAPTCHA" iframe)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, 'iframe[title="reCAPTCHA"]')))
wait.until(EC.element_to_be_clickable((By.ID, "recaptcha-anchor"))).click()
driver.switch_to.default_content()
# 2. Switch to the challenge iframe and solve rounds until it closes
wait.until(EC.frame_to_be_available_and_switch_to_it(
(By.XPATH, '//iframe[contains(@title, "challenge")]')))
for _ in range(5):
target = wait.until(EC.presence_of_element_located(
(By.CSS_SELECTOR, ".rc-imageselect-desc-wrapper strong"))).text.strip().lower()
question = QUESTION_IDS.get(target)
if not question:
print("unsupported target, reloading:", target)
driver.find_element(By.ID, "recaptcha-reload-button").click()
time.sleep(2)
continue
tiles = driver.find_elements(By.CSS_SELECTOR, "td.rc-imageselect-tile")
size = 450 if len(tiles) == 16 else 300
url = driver.find_element(By.CSS_SELECTOR, "td.rc-imageselect-tile img").get_attribute("src")
solution = classify(grid_image_b64(url, size), question)
for index in solution.get("objects", []):
tiles[index].click()
time.sleep(0.3)
time.sleep(1)
driver.find_element(By.ID, "recaptcha-verify-button").click()
time.sleep(3)
driver.switch_to.default_content()
frame = driver.find_element(By.XPATH, '//iframe[contains(@title, "challenge")]')
if not frame.is_displayed(): # challenge closed: passed
break
driver.switch_to.frame(frame)
driver.switch_to.default_content()
driver.find_element(By.ID, "recaptcha-demo-submit").click()
time.sleep(2)
print("passed" if "Verification Success" in driver.page_source else "not passed")
finally:
driver.quit()
  • A estrutura da página do reCAPTCHA muda com o tempo; ajuste os seletores se algum deixar de funcionar.
  • Cada imagem reconhecida gera cobrança de pontos (preços em reconhecimento de imagem do reCAPTCHA v2). Tarefas cuja verificação falhou após os cliques podem ser reportadas em até 1 hora para solicitar o reembolso de pontos.
  • Se a pergunta não estiver na tabela de correspondência, clique no botão de recarregar para trocar de desafio ou entre em contato com o suporte para pedir que seja adicionada.