Guias
Clique em imagens do hCaptcha 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 hCaptcha com Selenium 4 e resolve o desafio de imagens em grade 3×3 em um navegador real: lê a pergunta e as 9 imagens, pede ao reconhecimento de imagem do hCaptcha (HCaptchaClassification) quais são os alvos e simula os cliques.
O hCaptcha também tem desafios de clicar em uma posição e de arrastar, que retornam coordenadas em vez de células; veja reconhecimento de imagem do hCaptcha. Se não quiser escrever código, a extensão do navegador cobre todos esses tipos.
Preparação
Seção intitulada “Preparação”pip install requests seleniumexport YESCAPTCHA_CLIENT_KEY=your_client_key- Clique na caixa de seleção. Ela fica no iframe do hCaptcha cuja URL contém
frame=checkbox; entre nele e clique em#checkbox. - Mude para o iframe do desafio. Ele é o iframe cuja URL contém
frame=challenge. - Leia a pergunta. O texto de
.prompt-texté a pergunta; envie-o exatamente como está (recomenda-se mudar o idioma da interface do hCaptcha para chinês simplificado ou inglês). Se houver uma imagem de exemplo ao lado da pergunta, coloque-a também emanchors. - Obtenha as imagens. O
.task-image .imagede cada célula tem uma imagem como plano de fundo; baixe-as em ordem, converta para Base64 e monte a listaqueries. - Reconheça. Chame
createTaskcom o tipoHCaptchaClassification. Osobjectsretornados correspondem às células, uma a uma;trueindica um alvo. - Clique e envie. Clique nas células que são alvos e no botão de envio. Podem vir várias rodadas em sequência; repita os passos 3 a 6.
- Concluído. Após a aprovação, o campo
h-captcha-responseda página contém o token; envie-o junto com o formulário.
Código completo
Seção intitulada “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()Observações
Seção intitulada “Observações”- A estrutura da página do hCaptcha muda com frequência; se os seletores do código deixarem de funcionar, ajuste-os conforme a página real.
- Cada rodada reconhecida gera cobrança de pontos; rodadas em que nenhum alvo é encontrado não são cobradas. Se a verificação falhar após os cliques, você pode reportar em até 1 hora para solicitar o reembolso de pontos.
- Se uma pergunta nova retornar
ERROR_UNKNOWN_QUESTION, atualize para obter outro desafio ou entre em contato com o suporte.
© YesCaptcha