# การคลิกภาพ hCaptcha อัตโนมัติด้วย Selenium

> ใช้ Python, Selenium 4 และ HCaptchaClassification ทำ hCaptcha แบบภาพตาราง 3×3 ให้เสร็จในเบราว์เซอร์จริง ตั้งแต่คลิกช่องทำเครื่องหมาย อ่านคำถามและภาพทั้ง 9 ภาพ เรียก API คลิก และส่งคำตอบ พร้อมโค้ดตัวอย่างฉบับสมบูรณ์

Source: https://docs.yescaptcha.com/th/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/th/tasks/hcaptcha-classification.md) (`HCaptchaClassification`) ตรวจว่าภาพไหนเป็นเป้าหมาย แล้วจำลองการคลิก

hCaptcha ยังมีโจทย์แบบ “คลิกตำแหน่งที่กำหนด” และ “ลาก” ซึ่งคืนค่าเป็นพิกัดแทนที่จะเป็นช่อง ดูวิธีจัดการได้ที่ [การจดจำภาพ hCaptcha](https://docs.yescaptcha.com/th/tasks/hcaptcha-classification.md) หากไม่ต้องการเขียนโค้ด ใช้ [ส่วนขยายเบราว์เซอร์](https://docs.yescaptcha.com/th/extension.md) ได้เลย ซึ่งรองรับโจทย์เหล่านี้ทั้งหมด

## การเตรียมตัว

```bash
pip install requests selenium
export YESCAPTCHA_CLIENT_KEY=your_client_key
```

## ขั้นตอน

1.  **คลิกช่องทำเครื่องหมาย** ช่องนี้อยู่ใน iframe ของ hCaptcha ที่ URL มี `frame=checkbox` ให้สลับเข้าไปแล้วคลิก `#checkbox`
2.  **สลับไปยัง iframe ของโจทย์** โจทย์อยู่ใน iframe ที่ URL มี `frame=challenge`
3.  **อ่านคำถาม** ข้อความใน `.prompt-text` คือคำถาม ให้ส่งไปยัง API ตามต้นฉบับ (แนะนำให้เปลี่ยนภาษาของ hCaptcha เป็นจีนตัวย่อหรืออังกฤษ) หากมีภาพตัวอย่างขนาดเล็กอยู่ข้างคำถาม ให้ใส่ภาพนั้นใน `anchors` ด้วย
4.  **ดึงภาพ** พื้นหลังของ `.task-image .image` ในแต่ละช่องคือภาพหนึ่งภาพ ให้ดาวน์โหลดตามลำดับ แปลงเป็น Base64 แล้วสร้างรายการ `queries`
5.  **จดจำภาพ** เรียก `createTask` ด้วยประเภทงาน `HCaptchaClassification` ค่า `objects` ที่ได้จะตรงกับแต่ละช่องตามลำดับ ช่องที่เป็น `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 เปลี่ยนบ่อย หาก selector ในโค้ดใช้ไม่ได้ ให้ปรับตามหน้าเว็บจริง
-   การจดจำภาพแต่ละรอบจะหักพอยต์ รอบที่ไม่พบเป้าหมายจะไม่หักพอยต์ หากคลิกแล้วการตรวจสอบไม่ผ่าน สามารถ [รายงาน](https://docs.yescaptcha.com/th/api/report.md) ภายใน 1 ชั่วโมงเพื่อขอคืนพอยต์หลังรายงาน
-   หากพบคำถามใหม่และได้รับ `ERROR_UNKNOWN_QUESTION` ให้รีเฟรชเพื่อเปลี่ยนโจทย์ หรือติดต่อฝ่ายสนับสนุน
