Skip to content
CaptchaSonic

Python SDK

公式の CaptchaSonic SDK を使って Python から CAPTCHA を解決します。gRPC と HTTP のトランスポート、非同期に対応し、完全に型付けされています。

公式の CaptchaSonic Python SDK を使うと、対応しているすべての CAPTCHA を 1 回の関数呼び出しで解決できます。同期クライアント(CaptchaSonic)と非同期クライアント(AsyncCaptchaSonic)の両方を備えています。既定では gRPC で当社のインフラと通信し、オプションで HTTP トランスポートも利用できます。型ヒントを完全に備え、一時的なエラーには自動で再試行し、トークン型のチャレンジには組み込みのポーリングを使います。


インストール

pip install captchasonic

gRPC トランスポートは標準でインストールされます。オプションの HTTP/JSON トランスポートも使う場合は、追加パッケージをインストールしてください。

pip install "captchasonic[http]"

TIP

この SDK は Python 3.10、3.11、3.12、3.13 に対応しており、MIT ライセンスで公開されています。


認証

CaptchaSonic の API キーが必要です。アカウントを作成し、ダッシュボード からキーを取得してください。その後、残高の追加 から残高をチャージしてください。

キーをクライアントの最初の位置引数として渡します。

from captchasonic import CaptchaSonic

solver = CaptchaSonic("YOUR_API_KEY")

WARNING

API キーはパスワードと同じように扱ってください。ソース管理に含めないようにしてください。直接書き込まず、環境変数またはシークレットマネージャーから読み込んでください。

import os
from captchasonic import CaptchaSonic

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

クイックスタート

ほとんどのトークン型 CAPTCHA(reCAPTCHA、Turnstile、hCaptcha)は、1 回の呼び出しで解決できます。クライアントがポーリングを代行し、タスクの準備ができるとトークンを返します。

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

reCAPTCHA トークンを返します。ページの g-recaptcha-response として送信してください。

トークン型のメソッドは、既定では最大 120 秒までポーリングしてからタイムアウトします(設定 を参照)。


対応している CAPTCHA 種別

SDK のメソッドは、次の 2 つのファミリーに分かれます。

  • トークンメソッド(*_token、solve_turnstile、solve_cloudflare)— website_url / website_key を指定すると、SDK が当社のインフラをポーリングし、そのまま送信できる result["token"] を返します。
  • 画像 / インタラクティブメソッド — チャレンジの画像は自分で渡します。SDK は、クリック、ドラッグ、入力すべき内容を示す result["typed_solution"] を返します。

すべての画像引数は、柔軟な ImageInput 型を受け付けます。ファイルパス(str)、pathlib.Path、生の bytes、または開いたバイナリファイルオブジェクトを指定できます。

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(トークン)

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"]

result["token"] を返します。ページの g-recaptcha-response として送信してください。

reCAPTCHA v3(トークン)

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"]

result["token"] を返します。ページの g-recaptcha-response として送信してください。

reCAPTCHA v2(画像グリッド)

チャレンジのタイルがすでにある場合は、グリッドを直接解決して、クリックすべきインデックスを受け取ります。

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]

result["typed_solution"]["grid"]["objects"] を返します。クリックすべきタイルのインデックスの一覧です。

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"]

Turnstile トークンを返します。フォームの cf-turnstile-response として送信してください。

REST task typeAntiTurnstileTask

Cloudflare Challenge

Cloudflare の完全なチャレンジには、プロキシが 必須 です。

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

result["token"] を返します。保護されたリクエストに使うクリアランストークンです。

solve_popular_captcha はインタラクティブな画像バリアントを扱います。solve_popular_captcha_token はトークンを直接返します。

# 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"]

画像バリアントは result["typed_solution"]["grid"]["objects"](クリックするタイルのインデックス)を返します。トークンバリアントは 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

result["typed_solution"] を返します。実行すべきアクションで、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]

result["typed_solution"]["grid"]["objects"] を返します。クリックするタイルのインデックスの一覧です。

画像からテキスト(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

result["typed_solution"]["text"]["texts"][0] を返します。入力すべき認識済みのテキストです。

スライドパズル

背景とパズルのピースを渡すと、スライドさせる水平方向のピクセルオフセットが返ります。

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

result["typed_solution"]["slide"]["x"] を返します。ピースをドラッグする水平方向のピクセルオフセットです。

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"]

result["typed_solution"] を返します。実行すべきアクションで、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"]

result["typed_solution"] を返します。実行すべきアクションで、type によって形式が決まります。


非同期での利用

高い同時実行が必要なワークロード(FastAPI のハンドラー、Scrapy のスパイダー、asyncio のパイプライン)では、AsyncCaptchaSonic を使ってください。同期 API と完全に同じ構造ですが、すべての解決メソッドは await 可能です。非同期のコンテキストマネージャーとして使うと、基盤のチャネルが自動的にクリーンアップされます。

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())

同期クライアントもコンテキストマネージャーのプロトコルに対応しています。

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

プロキシのサポート

トークンメソッドは、任意の proxy 引数を受け付けます(solve_cloudflare では必須です)。標準のプロキシ URL を使ってください。

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

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

TIP

プロキシを指定すると、当社のソルバーがリクエストの地理的な位置と IP の評判を反映できるため、厳しいボット対策を行うサイトでの成功率が向上します。


設定

すべてのオプションはクライアントのコンストラクターに渡します。同期クライアントと非同期クライアントの両方に適用されます。

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
)
OptionDefaultDescription
transport"grpc"通信プロトコルです。"grpc" は Base64 のオーバーヘッドなしで画像を送信します。"http"([http] の追加パッケージが必要)は、Base64 エンコードした画像を REST/JSON で送信します。
urlapi.captchasonic.com:443API のエンドポイントを上書きします(セルフホスト環境やステージング環境向け)。
timeout30.01 回の呼び出しのネットワークタイムアウトです(秒)。
polling_interval2.0トークンタスクの待機中に、ポーリングする間隔(秒)です。
polling_timeout120.0例外を送出するまでにトークンタスクを待つ最大秒数です。
secureTruegRPC チャネルで TLS を使用します。

一時的な gRPC エラーは、指数バックオフで自動的に再試行されます(最大 3 回)。そのため、扱う必要があるのは実際のビジネスエラーだけです。


エラー処理

SDK のエラーはすべて SonicError を継承しています。そのため、1 つの except 節ですべてを捕捉することも、特定のサブクラスで分岐することもできます。各エラーは数値の error_id も持ちます。

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).


アカウントのヘルパー

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

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

サービス内で軽量な準備確認には health_check() を使い、クレジットを使い始める前にジョブを制御するには get_balance() を使ってください。


トラブルシューティング

TIP

HTTP トランスポート使用時に ModuleNotFoundError が出る。 HTTP クライアントは httpx に依存していますが、これはオプションの追加パッケージです。pip install "captchasonic[http]" でインストールし、transport="http" を設定してください。

  • トークンタスクが約 120 秒後にエラーになる。 これは polling_timeout によるものです。動作の遅いサイトでは値を大きくしてください(例: CaptchaSonic(key, polling_timeout=240.0))。
  • solve_cloudflare がすぐに失敗する。 Cloudflare のチャレンジには proxy 引数が必須です。有効なプロキシ URL を指定してください。
  • 企業のプロキシやファイアウォールの背後で gRPC の接続エラーが出る。 gRPC はポート 443 上の HTTP/2 を必要とします。ネットワークでブロックされている場合は、transport="http" に切り替えてください。
  • 画像メソッドがトークンではなくインデックスを返す。 インタラクティブなメソッド(solve_recaptcha_v2、solve_popular_captcha、solve_aws_waf、solve_geetest など)は、実行すべきアクションを示す result["typed_solution"] を返します。result["token"] を返すのは *_token、solve_turnstile、solve_cloudflare だけです。

リソース