# hCaptcha 画像認識によるクリック操作の自動化（Selenium）

> Python Selenium 4 と HCaptchaClassification を使い、ブラウザ上で hCaptcha の 3×3 グリッド画像チャレンジを自動で突破する方法を解説します。チェックボックスのクリック、問題文と 9 枚の画像の取得、認識 API の呼び出し、クリック、送信まで、完全なサンプルコード付きです。

Source: https://docs.yescaptcha.com/ja/guides/hcaptcha-click-selenium/ · Last verified: 2026-10-15

> This page was machine-translated from the Chinese version. If anything differs, the Chinese version prevails: https://docs.yescaptcha.com/zh/guides/hcaptcha-click-selenium/

このチュートリアルでは、Selenium 4 で hCaptcha のデモページを開き、実際のブラウザ上で 3×3 グリッドの画像チャレンジを突破します。問題文と 9 枚の画像を取得して [hCaptcha 画像認識](https://docs.yescaptcha.com/ja/tasks/hcaptcha-classification.md)（`HCaptchaClassification`）に渡し、どれが対象かを判定させたうえで、該当するタイルをクリックします。

hCaptcha には「指定位置をクリック」「ドラッグ」といった出題形式もあります。これらはタイルではなく座標を返します。処理方法は [hCaptcha 画像認識](https://docs.yescaptcha.com/ja/tasks/hcaptcha-classification.md) を参照してください。コードを書きたくない場合は [ブラウザ拡張機能](https://docs.yescaptcha.com/ja/extension.md) を使えば、これらの出題形式にもすべて対応できます。

## 準備

```bash
pip install requests selenium
export YESCAPTCHA_CLIENT_KEY=你的clientKey
```

## 手順

1.  **チェックボックスをクリックする。** チェックボックスは、URL に `frame=checkbox` を含む hCaptcha の iframe 内にあります。その iframe に切り替えて `#checkbox` をクリックします。
2.  **チャレンジの iframe に切り替える。** 問題は、URL に `frame=challenge` を含む iframe 内にあります。
3.  **問題文を読み取る。** `.prompt-text` のテキストが問題文です。そのままAPIに渡してください（hCaptcha の表示言語は英語または簡体字中国語に切り替えることを推奨します）。問題文の横に例示画像がある場合は、その画像も `anchors` に含めます。
4.  **画像を取得する。** 各タイルの `.task-image .image` の背景画像が 1 枚の画像です。順番にダウンロードして Base64 に変換し、`queries` のリストを作成します。
5.  **認識する。** タイプ `HCaptchaClassification` で `createTask` を呼び出します。返される `objects` は各タイルと 1 対 1 に対応しており、`true` のものが対象です。
6.  **クリックして送信する。** 対象のタイルをクリックし、送信ボタンを押します。続けて複数ラウンド出題されることがあるため、その場合は手順 3〜6 を繰り返します。
7.  **完了。** 通過すると、ページの `h-captcha-response` フィールドに token が入ります。フォームと一緒に送信してください。

## 完全なコード

hcaptcha_click_selenium.py

```python
"""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.py
Each 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 base64
import os
import re
import time

import requests
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://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 のページ構造は頻繁に変わります。コード内のセレクターが機能しなくなった場合は、実際のページに合わせて調整してください。
-   認識を行ったラウンドごとに課金されます。対象が見つからなかったラウンドは課金されません。クリック後に検証に失敗した場合は、1 時間以内に [報告](https://docs.yescaptcha.com/ja/api/report.md) すると、報告による返金を申請できます。
-   新しい問題で `ERROR_UNKNOWN_QUESTION` が返された場合は、ページを更新して別の問題に切り替えるか、サポートにお問い合わせください。
