Skip to content
CaptchaSonic

Python SDK

공식 CaptchaSonic SDK로 Python에서 CAPTCHA 풀기 — gRPC + HTTP 전송, 비동기 지원, 완전한 타입 힌트.

공식 CaptchaSonic Python SDK는 지원되는 모든 CAPTCHA를 함수 호출 한 번으로 처리합니다. 동기(CaptchaSonic) 클라이언트와 비동기(AsyncCaptchaSonic) 클라이언트를 모두 제공하며, 기본적으로 gRPC로 인프라와 통신합니다(선택적으로 HTTP 전송도 사용 가능). 전체 타입 힌트, 일시적 오류에 대한 자동 재시도, 토큰 방식 챌린지를 위한 내장 폴링을 포함합니다.


설치

pip install captchasonic

gRPC 전송은 기본으로 설치됩니다. 선택 기능인 HTTP/JSON 전송도 사용하려면 extra를 설치하세요:

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)는 호출 한 번으로 풀 수 있습니다. 클라이언트가 대신 폴링하고, 작업이 준비되면 토큰을 반환합니다.

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 메서드는 두 가지 계열로 나뉩니다:

  • 토큰 메서드(*_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"]을 반환합니다. 보호된 요청에 사용하는 clearance 토큰입니다.

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
)
옵션기본값설명
transport"grpc"와이어 프로토콜. "grpc"는 base64 오버헤드 없이 이미지를 전송하고, "http"([http] extra 필요)는 base64 인코딩된 이미지로 REST/JSON을 전송합니다.
urlapi.captchasonic.com:443API 엔드포인트 재정의(예: 자체 호스팅 또는 스테이징).
timeout30.0호출당 네트워크 시간 제한(초).
polling_interval2.0토큰 작업을 기다리는 동안 폴링 간격(초).
polling_timeout120.0예외를 던지기 전 토큰 작업을 기다리는 최대 시간(초).
secureTruegRPC 채널에 TLS 사용.

일시적인 gRPC 오류는 지수 백오프로 자동 재시도됩니다(최대 3회). 따라서 실제 비즈니스 오류만 처리하면 됩니다.


오류 처리

모든 SDK 오류는 SonicError를 상속하므로, 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 클라이언트는 선택 extra인 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뿐입니다.

리소스