Skip to content
CaptchaSonic

SDK Python

Giải CAPTCHA từ Python với SDK CaptchaSonic chính thức — truyền tải gRPC + HTTP, sẵn sàng bất đồng bộ, có kiểu đầy đủ.

SDK Python chính thức của CaptchaSonic biến mọi loại CAPTCHA được hỗ trợ thành một lệnh gọi hàm duy nhất. SDK cung cấp cả client đồng bộ (CaptchaSonic) lẫn bất đồng bộ (AsyncCaptchaSonic), giao tiếp với hạ tầng của chúng tôi qua gRPC theo mặc định (có thể chọn truyền tải HTTP), và đi kèm đầy đủ type hint, tự động thử lại với lỗi tạm thời, và thăm dò kết quả tích hợp sẵn cho các thử thách dạng token.


Cài đặt

pip install captchasonic

Truyền tải gRPC được cài sẵn. Để dùng thêm truyền tải HTTP/JSON tùy chọn, hãy cài phần mở rộng:

pip install "captchasonic[http]"

TIP

SDK hỗ trợ Python 3.10, 3.11, 3.12 và 3.13 và được phát hành theo giấy phép MIT.


Xác thực

Bạn cần một API key của CaptchaSonic. Tạo tài khoản và lấy key từ bảng điều khiển, sau đó nạp số dư từ Nạp tiền.

Truyền key làm tham số vị trí đầu tiên cho client:

from captchasonic import CaptchaSonic

solver = CaptchaSonic("YOUR_API_KEY")

WARNING

Hãy coi API key như mật khẩu. Không đưa key vào kiểm soát phiên bản — hãy tải từ biến môi trường hoặc trình quản lý bí mật thay vì ghi cứng.

import os
from captchasonic import CaptchaSonic

solver = CaptchaSonic(os.environ["CAPTCHASONIC_API_KEY"])

Bắt đầu nhanh

Phần lớn CAPTCHA dạng token (reCAPTCHA, Turnstile, hCaptcha) được giải bằng một lệnh gọi duy nhất. Client tự thăm dò và trả về token khi tác vụ sẵn sàng.

solve_recaptcha_v2_tokentoken
Verified v1.0.0· 2026-05-28

reCAPTCHA v2 (token) — Solve a reCAPTCHA v2 token challenge via browser automation (async — polls until ready).

signaturesolve_recaptcha_v2_token(…)returnssolution.token
from captchasonic import CaptchaSonic

solver = CaptchaSonic("YOUR_API_KEY")

result = solver.solve_recaptcha_v2_token(
    website_url="https://example.com/login",
    website_key="6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
)

print(result["token"])
# 03AGdBq25SxXT...  ← drop this into the g-recaptcha-response field

Trả về token reCAPTCHA — gửi nó làm g-recaptcha-response của trang.

Các phương thức dạng token thăm dò tối đa 120 giây theo mặc định trước khi hết thời gian (xem Cấu hình).


Các loại CAPTCHA được hỗ trợ

SDK chia các phương thức thành hai nhóm:

  • Phương thức token (*_token, solve_turnstile, solve_cloudflare) — bạn cung cấp website_url / website_key, SDK thăm dò hạ tầng của chúng tôi và trả về result["token"] sẵn sàng để gửi.
  • Phương thức ảnh / tương tác — bạn tự cung cấp ảnh thử thách, và SDK trả về result["typed_solution"] mô tả hành động cần click, kéo hoặc nhập.

Mọi tham số ảnh đều nhận kiểu ImageInput linh hoạt — đường dẫn tệp (str), pathlib.Path, bytes thô, hoặc một đối tượng tệp nhị phân đang mở.

from pathlib import Path

# Any of these work as an item in an `images=[...]` list:
Path("captcha.png")        # pathlib.Path
"./captcha.png"            # str path
open("captcha.png", "rb").read()  # bytes

reCAPTCHA v2 (token)

solve_recaptcha_v2_tokentoken
Verified v1.0.0· 2026-05-28

reCAPTCHA v2 (token) — Solve a reCAPTCHA v2 token challenge via browser automation (async — polls until ready).

signaturesolve_recaptcha_v2_token(…)returnssolution.token
result = solver.solve_recaptcha_v2_token(
    website_url="https://example.com",
    website_key="6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-",
    proxy="http://user:pass@host:port",  # optional
)
token = result["token"]

Trả về result["token"] — gửi nó làm g-recaptcha-response của trang.

reCAPTCHA v3 (token)

result = solver.solve_recaptcha_v3_token(
    website_url="https://example.com",
    website_key="6Lc_aCMTAAAAAB...",
    proxy="http://user:pass@host:port",  # optional
)
token = result["token"]

Trả về result["token"] — gửi nó làm g-recaptcha-response của trang.

reCAPTCHA v2 (lưới ảnh)

Khi bạn đã có sẵn các ô của thử thách, hãy giải lưới trực tiếp và nhận về các chỉ số cần click.

result = solver.solve_recaptcha_v2(
    images=[Path("tile.png")],         # ImageInput list
    question="traffic lights",          # label or /m/... entity id
    question_type="44",                # "split_33" | "33" | "44"
)
to_click = result["typed_solution"]["grid"]["objects"]  # list[int]

Trả về result["typed_solution"]["grid"]["objects"] — danh sách chỉ số ô cần click.

Cloudflare Turnstile

solve_turnstiletoken
Verified v1.0.0· 2026-05-28

Cloudflare Turnstile — Solve a Cloudflare Turnstile token challenge (async — polls until ready).

signaturesolve_turnstile(…)returnssolution.token
result = solver.solve_turnstile(
    website_url="https://example.com",
    website_key="0x4AAAAAAA...",
    proxy="http://user:pass@host:port",  # optional
)
token = result["token"]

Trả về token Turnstile — gửi nó làm cf-turnstile-response của form.

REST task typeAntiTurnstileTask

Thử thách Cloudflare

Thử thách Cloudflare đầy đủ bắt buộc phải có proxy.

result = solver.solve_cloudflare(
    website_url="https://example.com",
    website_key="0x4AAAAAAA...",
    proxy="http://user:pass@host:port",  # required
)
token = result["token"]

Trả về result["token"] — token clearance cho yêu cầu được bảo vệ.

solve_popular_captcha xử lý các biến thể ảnh tương tác; solve_popular_captcha_token trả về token trực tiếp.

# Image / interactive variant
result = solver.solve_popular_captcha(
    images=[Path("challenge.png")],
    question="Select all traffic lights",
    question_type="grid",  # "objectClassify" | "objectClick" | "objectDrag" | "grid"
)
to_click = result["typed_solution"]["grid"]["objects"]  # list[int]

# Token variant
result = solver.solve_popular_captcha_token(
    website_url="https://example.com",
    website_key="00000000-0000-0000-0000-000000000000",
    proxy="http://user:pass@host:port",  # optional
)
token = result["token"]

Biến thể ảnh trả về result["typed_solution"]["grid"]["objects"] (chỉ số ô cần click); biến thể token trả về result["token"].

GeeTest

result = solver.solve_geetest(
    geetest_type="nine",  # "nine" | "click" | "slide" | "match" | "winlinze"
    question="Select all bicycles",  # required for "nine" and "click"
    images=[Path("tile.png")],        # required for "nine", "click", "slide"
)
solution = result["typed_solution"]  # structure varies by geetest_type

Trả về result["typed_solution"] — hành động cần thực hiện, có cấu trúc theo geetest_type.

AWS WAF

result = solver.solve_aws_waf(
    images=[Path("grid.png")],
    question="grid:vehicles:cars",
)
to_click = result["typed_solution"]["grid"]["objects"]  # list[int]

Trả về result["typed_solution"]["grid"]["objects"] — danh sách chỉ số ô cần click.

Ảnh sang văn bản (OCR)

result = solver.solve_ocr(
    images=[Path("captcha.png")],
    module="common",       # "common" | "mtcaptcha" | "bls" | "morocco"
    numeric=False,         # expect only digits
    case_sensitive=True,   # preserve letter case
    min_length=4,
    max_length=8,
)
text = result["typed_solution"]["text"]["texts"][0]  # str

Trả về result["typed_solution"]["text"]["texts"][0] — văn bản đã nhận dạng để nhập vào.

Ghép hình trượt

Truyền ảnh nền và mảnh ghép; bạn nhận lại độ lệch pixel theo chiều ngang để kéo trượt.

result = solver.solve_slide_image(
    images=[Path("background.png"), Path("piece.png")],
)
offset_x = result["typed_solution"]["slide"]["x"]  # float (pixels)

Trả về result["typed_solution"]["slide"]["x"] — độ lệch pixel theo chiều ngang để kéo mảnh ghép.

TikTok

result = solver.solve_tiktok(
    type="whirl",  # "click" | "whirl" | "slide"
    images=[Path("outer.png")],
    examples=[Path("inner.png")],  # required for "whirl" and "slide"
)
solution = result["typed_solution"]

Trả về result["typed_solution"] — hành động cần thực hiện, có cấu trúc theo type.

Binance

result = solver.solve_binance(
    type="grid",  # "grid" | "slide"
    question="Select all bicycles",  # required for "grid"
    images=[Path("grid.png")],
)
solution = result["typed_solution"]

Trả về result["typed_solution"] — hành động cần thực hiện, có cấu trúc theo type.


Sử dụng bất đồng bộ

Với khối lượng công việc đồng thời cao (handler FastAPI, spider Scrapy, pipeline asyncio), hãy dùng AsyncCaptchaSonic. API của nó giống hệt bản đồng bộ, nhưng mọi phương thức giải đều có thể await. Dùng nó như một async context manager để kênh kết nối bên dưới được dọn dẹp tự động.

import asyncio
from captchasonic import AsyncCaptchaSonic

async def main():
    async with AsyncCaptchaSonic("YOUR_API_KEY") as solver:
        result = await solver.solve_turnstile(
            website_url="https://example.com",
            website_key="0x4AAAAAAA...",
        )
        print(result["token"])

asyncio.run(main())

Client đồng bộ cũng hỗ trợ giao thức context manager:

with CaptchaSonic("YOUR_API_KEY") as solver:
    result = solver.solve_ocr(images=[Path("captcha.png")])
    print(result["typed_solution"]["text"]["texts"][0])

Hỗ trợ proxy

Các phương thức token nhận tham số proxy tùy chọn (bắt buộc với solve_cloudflare). Sử dụng URL proxy tiêu chuẩn:

proxy = "http://user:pass@host:port"

result = solver.solve_recaptcha_v2_token(
    website_url="https://example.com",
    website_key="6Le-...",
    proxy=proxy,
)

TIP

Cung cấp proxy giúp solver của chúng tôi phản chiếu vị trí địa lý và uy tín IP của yêu cầu bạn, từ đó nâng tỷ lệ thành công trên các trang có quy tắc chống bot nghiêm ngặt.


Cấu hình

Mọi tùy chọn đều được truyền vào constructor của client và áp dụng cho cả client đồng bộ lẫn bất đồng bộ.

solver = CaptchaSonic(
    "YOUR_API_KEY",
    transport="grpc",                # "grpc" (default) or "http"
    url="api.captchasonic.com:443",  # endpoint override (optional)
    timeout=30.0,                    # per-call timeout, seconds
    polling_interval=2.0,            # seconds between task polls
    polling_timeout=120.0,           # max wait for a token task, seconds
    secure=True,                     # use TLS for gRPC
)
Tùy chọnMặc địnhMô tả
transport"grpc"Giao thức truyền dữ liệu. "grpc" gửi ảnh không tốn thêm chi phí base64; "http" (cần phần mở rộng [http]) gửi REST/JSON với ảnh mã hóa base64.
urlapi.captchasonic.com:443Ghi đè endpoint API (ví dụ cho máy chủ tự host hoặc staging).
timeout30.0Thời gian chờ mạng cho mỗi lệnh gọi, tính bằng giây.
polling_interval2.0Số giây giữa các lần thăm dò khi chờ một tác vụ token.
polling_timeout120.0Số giây tối đa chờ một tác vụ token trước khi ném lỗi.
secureTrueDùng TLS cho kênh gRPC.

Các lỗi gRPC tạm thời được tự động thử lại (tối đa 3 lần) với thời gian chờ tăng dần theo cấp số nhân, nên bạn chỉ cần xử lý các lỗi nghiệp vụ thực sự.


Xử lý lỗi

Mọi lỗi của SDK đều kế thừa từ SonicError, nên bạn có thể bắt tất cả bằng một mệnh đề except hoặc rẽ nhánh theo lớp con cụ thể. Mỗi lỗi cũng mang một error_id dạng số.

from captchasonic.exceptions import (
    SonicError,
    InvalidApiKeyError,
    InsufficientBalanceError,
)

try:
    result = solver.solve_turnstile(
        website_url="https://example.com",
        website_key="0x4AAAAAAA...",
    )
except InsufficientBalanceError:
    print("Top up your balance to continue.")
except InvalidApiKeyError:
    print("Check your API key.")
except SonicError as err:
    print(f"Solve failed (error_id={err.error_id}): {err}")
errors7 canonical `errorId` codes
idPython exceptionNode errorNameMeaningAction
0SonicErrorSonicErrorBase class for every SDK error — catches anything below.Inspect `error.errorId` (Node) / `err.error_id` (Python) and branch.
1InvalidApiKeyErrorInvalidApiKeyErrorAPI key is missing, malformed, or revoked.Verify the key in your dashboard.
2InsufficientBalanceErrorInsufficientBalanceErrorAccount balance can't cover the task.Add funds.
3DailyLimitExceededErrorDailyLimitExceededErrorDaily quota exhausted.Wait for the daily reset or upgrade your plan.
4MinuteLimitExceededErrorMinuteLimitExceededErrorPer-minute rate limit hit.Slow down requests / add exponential backoff.
5QuotaExceededErrorQuotaExceededErrorPlan quota exhausted.Upgrade your plan.
6PlanExpiredErrorPlanExpiredErrorSubscription has expired.Renew your subscription.

Every concrete row inherits from SonicError — catch it once to handle all SDK failures, or branch on errorId / exception subclass for granular control. Transient gRPC errors are retried automatically with exponential backoff (up to 3 attempts).


Hàm hỗ trợ tài khoản

balance = solver.get_balance()  # current balance in USD (float)
print(f"Balance: ${balance:.2f}")

health = solver.health_check()  # HealthCheckResponse — verifies connectivity

Dùng health_check() như một probe sẵn sàng nhẹ trong các service, và get_balance() để kiểm tra điều kiện trước khi bắt đầu công việc tiêu tốn credit.


Khắc phục sự cố

TIP

ModuleNotFoundError khi dùng truyền tải HTTP. Client HTTP phụ thuộc vào httpx, là một phần mở rộng tùy chọn. Hãy cài bằng pip install "captchasonic[http]" và đặt transport="http".

  • Tác vụ token báo lỗi sau khoảng 120 giây. Đó là polling_timeout. Hãy tăng giá trị này cho các đích chậm, ví dụ CaptchaSonic(key, polling_timeout=240.0).
  • solve_cloudflare lỗi ngay lập tức. Tham số proxy là bắt buộc với thử thách Cloudflare — hãy cung cấp một URL proxy hoạt động.
  • Lỗi kết nối gRPC sau proxy/tường lửa doanh nghiệp. gRPC cần HTTP/2 qua cổng 443. Nếu mạng của bạn chặn, hãy chuyển sang transport="http".
  • Phương thức ảnh trả về chỉ số, không phải token. Các phương thức tương tác (solve_recaptcha_v2, solve_popular_captcha, solve_aws_waf, solve_geetest, v.v.) trả về result["typed_solution"] mô tả hành động cần thực hiện; chỉ *_token, solve_turnstile và solve_cloudflare mới trả về result["token"].

Tài nguyên