API 教程

使用 CaptchaAI calc 参数进行数学验证码求解

数学验证码显示算术方程并期望计算结果 - 而不是方程文本。calc 参数告诉 CaptchaAI 求解数学并返回答案。


计算器的工作原理

计算值 行为
0(默认) 按原样返回文本(例如 "3+7"
1 计算结果并返回(例如,"10"

基本数学验证码解决

import requests
import base64
import time
import os

API_KEY = os.environ["CAPTCHAAI_API_KEY"]


def solve_math_captcha(image_b64):
    """Solve a math CAPTCHA — returns the computed result."""
    resp = requests.post("https://ocr.captchaai.com/in.php", data={
        "key": API_KEY,
        "method": "base64",
        "body": image_b64,
        "calc": 1,          # Compute the math
        "numeric": 1,       # Result will be a number
        "json": 1,
    }, timeout=30)

    result = resp.json()
    if result.get("status") != 1:
        raise RuntimeError(result.get("request"))

    task_id = result["request"]

    time.sleep(8)
    for _ in range(24):
        resp = requests.get("https://ocr.captchaai.com/res.php", params={
            "key": API_KEY, "action": "get",
            "id": task_id, "json": 1,
        }, timeout=15)
        data = resp.json()
        if data.get("status") == 1:
            return data["request"]
        if data["request"] != "CAPCHA_NOT_READY":
            raise RuntimeError(data["request"])
        time.sleep(5)

    raise TimeoutError("Solve timeout")


# Example: Image shows "3 + 7 = ?"
# With calc=0: Returns "3+7"
# With calc=1: Returns "10"

常见的数学验证码格式

Format              Example        Result
─────────────────────────────────────────
Addition            3 + 7 = ?      10
Subtraction         15 - 8 = ?     7
Multiplication      4 × 6 = ?      24
Division            20 ÷ 5 = ?     4
Mixed               3 + 4 × 2 = ?  11
Text-based          "three plus five"  8

有文字说明

对于复杂格式,添加说明:

def solve_text_math_captcha(image_b64, instructions):
    """Solve a math CAPTCHA with custom instructions."""
    resp = requests.post("https://ocr.captchaai.com/in.php", data={
        "key": API_KEY,
        "method": "base64",
        "body": image_b64,
        "calc": 1,
        "textinstructions": instructions,
        "json": 1,
    }, timeout=30)
    return resp.json()


# Example instructions:
# "Solve the math expression and enter the number"
# "What is the result of the equation shown?"
# "Enter the sum of the two numbers"

处理边缘情况

# edge_cases.py


def validate_math_result(answer):
    """Validate and clean math CAPTCHA result."""
    if not answer:
        return None

    # Remove spaces
    answer = answer.strip()

    # Handle negative results
    if answer.startswith("-"):
        try:
            return str(int(answer))
        except ValueError:
            return answer

    # Handle decimal results
    try:
        num = float(answer)
        if num == int(num):
            return str(int(num))
        return str(num)
    except ValueError:
        return answer


def solve_math_with_fallback(image_b64):
    """Try calc=1, fall back to manual parsing if needed."""
    # Try with calc
    result = solve_math_captcha(image_b64)

    # Validate result is actually a number
    try:
        float(result)
        return result
    except (ValueError, TypeError):
        pass

    # Fallback: solve without calc and compute locally
    resp = requests.post("https://ocr.captchaai.com/in.php", data={
        "key": API_KEY,
        "method": "base64",
        "body": image_b64,
        "calc": 0,      # Get the expression text
        "json": 1,
    }, timeout=30)

    # ... poll for result ...
    expression = "3+7"  # Example OCR result

    # Safely evaluate
    return str(safe_eval(expression))


def safe_eval(expression):
    """Safely evaluate a simple math expression."""
    # Only allow digits and basic operators
    import re
    cleaned = expression.replace("×", "*").replace("÷", "/").replace("=", "").replace("?", "")
    cleaned = cleaned.strip()

    if not re.match(r'^[\d\s+\-*/().]+$', cleaned):
        raise ValueError(f"Unsafe expression: {expression}")

    return eval(cleaned)  # Safe because we validated the pattern

完整流程

# full_flow.py
from selenium import webdriver
from selenium.webdriver.common.by import By
import base64
import os


def solve_math_captcha_on_page(driver, captcha_selector, input_selector, submit_selector):
    """Complete flow: capture math CAPTCHA, solve, enter answer."""

    # Capture CAPTCHA image
    captcha_el = driver.find_element(By.CSS_SELECTOR, captcha_selector)
    image_b64 = captcha_el.screenshot_as_base64

    # Solve with calc=1
    answer = solve_math_captcha(image_b64)
    print(f"Math answer: {answer}")

    # Enter the computed result
    input_el = driver.find_element(By.CSS_SELECTOR, input_selector)
    input_el.clear()
    input_el.send_keys(answer)

    # Submit
    driver.find_element(By.CSS_SELECTOR, submit_selector).click()


# Usage
driver = webdriver.Chrome()
driver.get("https://example.com/form")

solve_math_captcha_on_page(
    driver,
    captcha_selector="#captcha-image",
    input_selector="#captcha-answer",
    submit_selector="#submit-btn",
)

故障排除

问题 原因 处理方式
返回表达式而不是结果 缺少 calc=1 添加 calc=1 提交
结果错误 运算符误读(× vs +) 添加 textinstructions 描述方程格式
返回整数方程的小数 浮点 转换为 int:str(int(float(result)))
ERROR_CAPTCHA_UNSOLVABLE 非常扭曲的方程 首先尝试对图像进行预处理

常问问题

calc 可以处理复杂的表达式吗?

CaptchaAI 处理基本算术(+、-、×、×)。对于带有括号或指数的复杂表达式,请使用 calc=0 并在本地解析表达式。

如果结果是否定的怎么办?

CaptchaAI 正确返回负数(例如,"5 - 8 = ?" 返回 "-3")。

calc 可以与基于文本的数学一起使用吗?

如果验证码显示“三加五”,请使用 textinstructions 暗示它是基于文本的数学。结果可能会有所不同。


相关指南


自动解决数学验证码 -以 CaptchaAI 开头.

该文章已禁用评论。