GeeTest v4 in Python: Read the ID Once, Solve Every Post

geetest v4 in python - GeeTest v4 in Python: Read the ID Once, Solve Every Post

GeeTest v4 in Python comes down to one id and one call per form post. Read the captcha_id off the page a single time, ask solver.geetest_v4() from the CapSkip SDK for a pass, and send the five values it returns, captcha_id, lot_number, pass_token, gen_time and captcha_output, back under those same names. The CapSkip GeeTest v4 solver does the solving on your own Windows PC under a flat license, so a refused pass costs another solve and no extra fee. Nothing has to be fetched before each attempt, which is the difference from the gt and challenge pair in the GeeTest v3 flow.

What you need before solving GeeTest v4

  • CapSkip 5.0.0 or newer on Windows (the changelog lists GeeTest v4 solving there, 14 November 2026) and Python SDK 1.8.0 or newer (16 November 2026). The GeeTest v4 section of the API docs describes the request.
  • Python 3.10 or newer, the floor declared by capskip 1.8.0 and requests 2.34.2. The versions I ran were Python 3.11.7, 3.13.7 and 3.14.0 on Windows 11. Install both packages with python -m pip install capskip requests. The capskip package also installs httpx and aiofiles, which only the async client uses.
  • An address for CapSkip. Local mode (127.0.0.1) is reachable only from the PC that runs it. In Server mode it listens on your network or public IP instead, so scripts on other machines can reach it. The connection settings section of the setup guide shows where the mode is switched.

I tested with two mock servers of my own, a stand-in for CapSkip and a stand-in for a site with a comment form. No real solve happened, so I have no real solve time to give you, and every site rule in the mock is mine. On a real site the backend forwards the five values to GeeTest with a signature from its private key, as the GeeTest server API reference describes. A mock cannot show that a real backend accepts anything.

Step 1: find the captcha_id on the page

Save the first block as comment_geetest.py and add every later block at the end, in order. The file is finished after Step 3. Point PAGE_URL at the page that shows the widget. In Server mode, put the address of the CapSkip machine in host.

# python -m pip install capskip requests
import re

import requests
from capskip import ApiException, CapSkip

PAGE_URL = "https://example.com/comment"  # the page that shows the widget
FIELDS = ("captcha_id", "lot_number", "pass_token", "gen_time", "captcha_output")

# Local mode. In Server mode, use the address of the CapSkip machine.
solver = CapSkip(host="127.0.0.1", port=8080)

The captcha_id is public and identical for every visitor, so you read it once and reuse it. The page hands it to initGeetest4 as the captchaId option, and the widget script also sends it as the captcha_id query parameter of its request to gcaptcha4.geetest.com/load. The CapSkip GeeTest v4 page describes a 32-character id, but the SDK checks no format, so the pattern accepts any word characters or hyphens. It looks for the option by name instead of parsing the call, which survives nesting, single quotes and a different key order.

def read_captcha_id(html):
    """Return the captcha_id the page gives to the GeeTest v4 script."""
    for pattern in (
        r"\bcaptchaId[\"']?\s*:\s*[\"']([\w-]+)[\"']",  # initGeetest4({captchaId: ...})
        r"[?&]captcha_id=([\w-]+)",  # a gcaptcha4.geetest.com/load address
    ):
        found = re.search(pattern, html)
        if found:
            return found.group(1)
    raise RuntimeError("no captcha_id in the page, read it from the Network tab")


def open_session():
    session = requests.Session()
    page = session.get(PAGE_URL, timeout=30)  # cookies arrive with the page
    return session, read_captcha_id(page.text)

I ran read_captcha_id on six mock pages: the id in double quotes, in single quotes among other options, in a nested object with a quoted key that was not first, in a variable with the key last, only in a load address, and nowhere because a script builds the call at runtime. For that case, open the browser’s Network tab once, filter for gcaptcha4 and copy the captcha_id from the load request. I did not run the function against a real site.

Step 2: ask for a pass with geetest_v4()

The method signature is solver.geetest_v4(captcha_id, url, **options). The SDK submits the task, keeps polling until the answer is ready and hands back a dictionary, so no waiting loop is needed. The url is the full address of the page the widget sits on. The block below keeps just the five fields for the form, and adds risk_type only when you set it.

def pick(result):
    if result.get("isOffline"):
        print("offline pass: the site decides whether to accept it")
    missing = [name for name in FIELDS if name not in result]
    if missing:
        raise RuntimeError(f"GeeTest answer did not parse, missing {missing}")
    return {name: result[name] for name in FIELDS}


def get_pass(captcha_id, risk_type=None):
    options = {"risk_type": risk_type} if risk_type else {}
    return pick(solver.geetest_v4(captcha_id, PAGE_URL, **options))

The dictionary holds the five values as separate keys. It also holds captchaId, the number CapSkip gave the task, which is not the widget id: the form wants captcha_id with the underscore. The key code keeps the raw JSON string, which per the API docs is how res.php packs the five values. The SDK parses it for you, and against my mock, which follows the docs, code was a string that parsed to the five values. Post the separate fields, not code.

When GeeTest cannot be reached, its widget passes the visitor in offline mode and the dictionary also carries isOffline set to True. Otherwise the key is missing. The pick function prints a note and still returns the five fields, because the site decides whether to accept an offline pass.

The risk_type option is for sites that let the caller choose a challenge. The values, per the API docs, are slide, icon, nine, word, phrase, match, winlinze, svg_seed, svg_icon and ai, and GeeTest applies one only where the site allows it, so leave it out otherwise. The SDK checks only that it is a string: slide and nine reached the mock unchanged, riskType was renamed to risk_type, and an invented value such as risk_type=bogus went out too.

Before anything is sent, the SDK raises ValidationException for a missing, empty or non string captcha_id, a page address that is empty or not an absolute http or https URL, a risk_type that is not a string, riskType and risk_type with different values, and any option the API does not take. That includes userAgent, which the hCaptcha and MTCaptcha methods accept but this one does not, and the v3 names gt and challenge. Against a port with no server each of these raised in well under a hundredth of a second. The API docs give ERROR_PAGEURL and ERROR_BAD_PARAMETERS for the same mistakes, so a raw in.php caller sees those codes where you see an exception.

The geetest_v4() method runs a real browser inside CapSkip, so the SDK gives it recaptchaTimeout, 300 seconds by default, and not defaultTimeout. I checked both. With defaultTimeout at 3 seconds and a mock that never answered, the call was still polling after 9 seconds. With recaptchaTimeout at 3 it raised TimeoutException after 3.76 seconds, because the SDK asked at 0, 0.25, 0.76 and 1.76 seconds, slept 2 more and only then looked at the deadline. The same schedule delays a success: a pass ready after 1 second came back at 1.76, one ready after 2 seconds at 3.76 and one ready after 6 seconds at 7.76. These are Python 3.14.0, capskip 1.8.0 and default polling, against the mock. The CapSkip GeeTest v4 page quotes 1 to 4 seconds for a one click pass and about 15 to 20 for a slide, so size recaptchaTimeout for the slowest type your site may serve.

Step 3: post the five values, then solve again for the next post

Send the five values under the names above, next to your own fields, and compare with what the page’s own submit sends in the Network tab. The function also sends the page as Referer. The requests library adds neither Referer nor Origin, and some frameworks turn away an HTTPS form post that lacks both, as my mock did with a 403.

POST_URL = PAGE_URL  # the form's action address, if it differs from the page


def post_comment(session, fields, author, text):
    return session.post(
        POST_URL,
        data={"author": author, "comment": text, **fields},  # your form's own fields
        headers={"Referer": PAGE_URL},  # requests sends none by itself
        timeout=30,
    )

Solve again for every form post. The API docs say so, and my mock follows them: it refused a second post of the same five values as already used, and a pass posted 3 seconds after the solve when its lifetime was set to 2 seconds. So the loop asks for a pass inside the loop over comments, while the captcha_id comes from open_session once. It requests a new solve only on ERROR_CAPTCHA_UNSOLVABLE or when the site says the captcha check failed. Any other ApiException is raised, because a wrong key fails the same way again.

The refusal test is a whole phrase from your site, here captcha check failed. A test on the bare word captcha matched the comment page shown again after an empty comment, which still carries the widget markup, and spent three tasks on a mistake unrelated to the captcha. The shorter check failed matched the 403 page from the Referer check.

def submit_all(session, captcha_id, comments, passes=None):
    saved = 0
    for index, (author, text) in enumerate(comments):
        for attempt in range(1, 4):
            ready = passes[index] if passes and attempt == 1 else None
            try:
                fields = ready or get_pass(captcha_id)  # a new solve per form post
            except ApiException as err:
                if "ERROR_CAPTCHA_UNSOLVABLE" not in str(err):
                    raise  # a wrong key or a bad request fails again
                print(f"comment {index + 1}, attempt {attempt}: unsolvable, new task")
                continue
            reply = post_comment(session, fields, author, text)
            if "Comment saved" in reply.text:  # your site's success sign
                saved += 1
                break
            if "captcha check failed" not in reply.text.lower():  # your phrase
                raise RuntimeError(f"refused ({reply.status_code}), not the captcha")
            print(f"comment {index + 1}, attempt {attempt}: pass refused, new solve")
        else:
            raise RuntimeError(f"comment {index + 1}: no luck after 3 attempts")
    return saved


if __name__ == "__main__":
    session, captcha_id = open_session()
    comments = [("alice", "First"), ("alice", "Second"), ("alice", "Third")]
    print(submit_all(session, captcha_id, comments), "comments saved")

Run it with python comment_geetest.py (py comment_geetest.py works too). Against the mock, the script behaved the same on Python 3.11.7, 3.13.7 and 3.14.0:

Mock settingWhat happened
Three comments, defaultsThree tasks with the same captcha_id, three posts accepted
With a hand-written post: same five values posted twiceThe second post was refused as already used
With a hand-written post: pass posted 3 seconds after the solve, mock lifetime 2 secondsRefused as too old, and the next fresh solve went through
Two unsolvable answers at the startTwo retries, and the pass from the third task was accepted
Three unsolvable answers in a rowRuntimeError once three tasks were used
Offline pass, site accepts itNote printed, post accepted after one task
Offline pass, site refuses itThree tasks, then RuntimeError
Empty comment, page shown again with the widget markupRuntimeError after one task. With the bare word captcha as the test, three tasks
Form post without the Referer header403, RuntimeError after one task
Key validation on, SDK default keyApiException after one task. With the right apiKey, accepted

Read the table as a test of my mock and my script, not of GeeTest. The docs say to submit promptly and solve again for every form post. Single use and the two-second life are my mock’s rules.

Several posts at once with AsyncCapSkip

The async client earns its place for one reason: a pass takes seconds, and three can be requested together. AsyncCapSkip is built on httpx, so asyncio.gather overlaps the solves while the form posts stay in plain requests. With the mock taking 3.0 seconds per pass, three posts needed 11.35 seconds one solve after another and 4.09 seconds overlapped, on Python 3.14.0, with three tasks open at once in the mock.

Port 8080 in both blocks is the default of the 2captcha style service, so use the port shown in the CapSkip settings. For a larger pool pattern see the post on solving captchas in parallel with Python. Replace the main block from Step 3 with the one below. A failed solve becomes None in solve_all and submit_all asks again with a single call, so a wrong key still ends in the same ApiException. Request only as many passes as you can post while they are fresh, and batch a long list.

import asyncio

from capskip import AsyncCapSkip


async def solve_all(captcha_id, count):
    # Local mode. In Server mode, use the address of the CapSkip machine.
    async_solver = AsyncCapSkip(host="127.0.0.1", port=8080)
    jobs = [async_solver.geetest_v4(captcha_id, PAGE_URL) for _ in range(count)]
    results = await asyncio.gather(*jobs, return_exceptions=True)
    return [pick(r) if isinstance(r, dict) else None for r in results]


def submit_overlapped(comments):
    session, captcha_id = open_session()
    passes = asyncio.run(solve_all(captcha_id, len(comments)))
    return submit_all(session, captcha_id, comments, passes)


if __name__ == "__main__":
    comments = [("alice", "First"), ("alice", "Second"), ("alice", "Third")]
    print(submit_overlapped(comments), "comments saved")

Common errors

The CapSkip codes come from the API docs, the exception rows from the SDK source, and the last row is my reading of the docs line to solve again for every form submission.

ErrorCauseFix
ValidationExceptionThe SDK refused the arguments on your machine without contacting CapSkip, for one of the reasons in Step 2The exception text points at the offending argument
ERROR_CAPTCHA_UNSOLVABLEThe pass could not be obtained for that taskSubmit a new task, as submit_all does for up to three tries. The docs say the app may return replacement text set in Settings, so match that text if you changed it
ERROR_KEY_DOES_NOT_EXIST or ERROR_WRONG_USER_KEYThe app checks keys (API Key Validation) and yours is absent or wrong. Calls without apiKey use the key capskip, which the mock answered with the first codePass your real key as apiKey to CapSkip()
ERROR_PROXY_FORMATThe docs list it for a proxy value CapSkip cannot read, and ask for no scheme prefix. The SDK sent a prefixed value unchangedWrite login:password@IP:PORT without http://
NetworkExceptionNo answer from that host and port when the task goes out, which I saw after about 2 seconds on Windows. A server that goes quiet mid-poll gives TimeoutException insteadMake sure CapSkip is open and that host and port match the connection settings
TimeoutExceptionNo pass arrived within recaptchaTimeout, 300 seconds unless you set another valueLook at the task in the CapSkip app and run the script again
The site says the captcha check failedMy inference, not a documented list: the five values were used before, were too old or were alteredPost each set once and right away, unchanged, with the page as Referer

FAQ

Can I call CapSkip from a different computer?

Yes, through Server mode. Switch it on in the connection settings of the CapSkip PC, then give that PC’s address as host to CapSkip(), plus your key as apiKey if API Key Validation is on. Server mode opens the CapSkip port to every address when it starts, so a Windows Firewall block rule for the machines you don’t trust is what keeps others out. Another allow rule would change nothing. It is still your own Windows machine, and still unmetered.

Do I need a proxy for GeeTest v4?

Not to start. The API docs call one address fine for testing, and say that a steady stream from one address is what the GeeTest rate limiting targets. For volume, load a proxy pool in the app, or give a task its own proxy, which wins over the pool. The post on proxies for a captcha solver covers choosing one. In Python the option is either a dictionary, proxy={"type": "HTTP", "uri": "login:password@IP:PORT"}, or a plain string with proxytype beside it. Both shapes reached the mock as proxy and proxytype fields.

What if the page gives me a gt and a challenge instead?

Then the site runs GeeTest v3, which needs a fresh challenge for every attempt and returns challenge, validate and seccode. That flow is covered in the post on GeeTest v3 in Python.

The short version

GeeTest v4 in Python is one captcha_id read once, one solve for each form post and five fields sent back unchanged. Because CapSkip is an unlimited captcha solver that runs on your own PC, a repeated solve adds nothing to a bill. The Python CAPTCHA solver page lists the SDK calls for the other types.