Quay Lại BlogHướng Dẫn

Giải reCAPTCHA v3 với Python: Hướng Dẫn Từng Bước

Học cách tích hợp giải CAPTCHA vào script Python sử dụng async requests, logic retry và xử lý lỗi sẵn sàng cho production.

Đội ngũ reGOTCHA19 tháng 12, 20256 phút đọc
Giải reCAPTCHA v3 với Python: Hướng Dẫn Từng Bước

Yêu Cầu

  • Python 3.8 trở lên
  • Tài khoản reGOTCHA với API key
  • Hiểu biết cơ bản về lập trình async

Cài Đặt

terminal
pip install httpx asyncio

Ví Dụ Đồng Bộ Cơ Bản

Bắt đầu với triển khai đồng bộ đơn giản:

example.py
import httpx
import time

API_KEY = "your-api-key"
BASE_URL = "https://api.regotcha.com"

def solve_recaptcha(website_url: str, website_key: str, action: str = "submit"):
    # Tạo task
    response = httpx.post(
        f"{BASE_URL}/createTask",
        json={
            "clientKey": API_KEY,
            "task": {
                "type": "ReCaptchaV3EnterpriseTaskProxyless",
                "websiteURL": website_url,
                "websiteKey": website_key,
                "pageAction": action
            }
        }
    )
    task_id = response.json()["taskId"]

    # Polling kết quả
    while True:
        result = httpx.post(
            f"{BASE_URL}/getTaskResult",
            json={"clientKey": API_KEY, "taskId": task_id}
        ).json()

        if result["status"] == "ready":
            return result["solution"]["gRecaptchaResponse"]

        time.sleep(2)

# Sử dụng
token = solve_recaptcha(
    "https://example.com",
    "6LcR_RIpAAAAANGDwXhTz8nO4N_NijF_Pj2iO4L6",
    "login"
)
print(f"Token: {token}")

Triển Khai Async Sẵn Sàng Production

Cho khối lượng công việc production, sử dụng async với xử lý lỗi đúng cách:

example.py
import httpx
import asyncio
from typing import Optional

class RecaptchaSolver:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.regotcha.com"

    async def solve(
        self,
        website_url: str,
        website_key: str,
        action: str = "submit",
        timeout: int = 120
    ) -> Optional[str]:
        async with httpx.AsyncClient() as client:
            # Tạo task
            response = await client.post(
                f"{self.base_url}/createTask",
                json={
                    "clientKey": self.api_key,
                    "task": {
                        "type": "ReCaptchaV3EnterpriseTaskProxyless",
                        "websiteURL": website_url,
                        "websiteKey": website_key,
                        "pageAction": action
                    }
                }
            )
            data = response.json()

            if data.get("errorId"):
                raise Exception(f"Lỗi API: {data.get('errorDescription')}")

            task_id = data["taskId"]

            # Polling với timeout
            start = asyncio.get_event_loop().time()
            while asyncio.get_event_loop().time() - start < timeout:
                result = await client.post(
                    f"{self.base_url}/getTaskResult",
                    json={"clientKey": self.api_key, "taskId": task_id}
                )
                result_data = result.json()

                if result_data["status"] == "ready":
                    return result_data["solution"]["gRecaptchaResponse"]

                if result_data.get("errorId"):
                    raise Exception(f"Lỗi giải: {result_data.get('errorDescription')}")

                await asyncio.sleep(2)

            raise TimeoutError("Giải CAPTCHA quá thời gian")

# Sử dụng
async def main():
    solver = RecaptchaSolver("your-api-key")
    token = await solver.solve(
        "https://example.com",
        "6LcR_RIpAAAAANGDwXhTz8nO4N_NijF_Pj2iO4L6",
        "checkout"
    )
    print(f"Token: {token}")

asyncio.run(main())

Xử Lý Hàng Loạt

Giải nhiều CAPTCHA đồng thời:

example.py
async def solve_batch(solver, tasks):
    """Giải nhiều CAPTCHA đồng thời"""
    return await asyncio.gather(
        *[solver.solve(**task) for task in tasks],
        return_exceptions=True
    )

# Ví dụ: Giải 10 CAPTCHA song song
tasks = [
    {"website_url": "https://site1.com", "website_key": "key1", "action": "login"},
    {"website_url": "https://site2.com", "website_key": "key2", "action": "signup"},
    # ... thêm tasks
]

results = await solve_batch(solver, tasks)
Mẹo Hiệu Suất: Cho khối lượng công việc lớn, giữ kết nối AsyncClient và tái sử dụng qua các request để giảm overhead kết nối.
PythonHướng dẫnAPICode

Sẵn sàng giải quyết CAPTCHA theo quy mô?

Bắt đầu với 50 tín dụng miễn phí. Không cần thẻ tín dụng.