Yandex SmartCaptcha in Python: Playwright and AsyncCapSkip

yandex smartcaptcha in python - Yandex SmartCaptcha in Python: Playwright and AsyncCapSkip

To handle Yandex SmartCaptcha in Python with a real browser, open the sign-up page in Playwright, read the data-sitekey off the widget’s container, pass it and the page address to the yandex_smart() call of AsyncCapSkip, write the token it returns into the hidden smart-token field and click submit. The solve runs in the CapSkip Yandex SmartCaptcha solver on your own Windows PC under a flat license, so a refused token costs you another pass through the loop and nothing else.

What you need

  • CapSkip 5.0.0 or later on a Windows PC. Version 5.0.0 came out on 14 November 2026 and was the first to solve Yandex SmartCaptcha. The setup guide walks through installing it. I could not reach a running CapSkip when I wrote this, so every run below used a mock.
  • Python 3.10 or newer, the floor declared by capskip 1.8.0 (the first version with yandex_smart) and by playwright 1.65.2. My runs covered Python 3.11.7, 3.13.7 and 3.14.0 and nothing else.
  • Both packages install from PowerShell with python -m pip install capskip playwright. Then python -m playwright install chromium fetches the browser. The script below starts the full Chromium build, which that command includes.
  • An address for CapSkip. In Local mode, 127.0.0.1, only the PC running CapSkip can reach it. Server mode makes it listen on your network or public IP, so a second PC or a Windows VPS can send tasks. Both are covered in the connection settings section of the setup guide. If you turned API Key Validation on in CapSkip, give the constructor your key as apiKey.

Everything below ran against two mocks I wrote: one plays CapSkip, the other plays a sign-up site whose widget is a stand-in script of mine. Nothing was sent to Yandex or to any real CAPTCHA site, so no real token, no real solve time and no real acceptance appears here, and every site rule is mine. On a live site the check belongs to that site’s own server, which sends the token and its secret key to Yandex, as the Yandex Cloud validation docs explain how the check works.

Step 1: create the solver and locate the sitekey

Save the first block as yandex_signup.py and append every later block to it in the order shown. The file is complete once Step 4 is in. For Server mode, replace the host with your server’s address.

# python -m pip install capskip playwright
# python -m playwright install chromium
import asyncio
import sys
from urllib.parse import parse_qs, urlsplit

from capskip import ApiException, AsyncCapSkip
from playwright.async_api import async_playwright

SIGNUP_URL = "https://example.com/signup"  # the page that shows the widget

# Local mode. In Server mode, use your server's address as the host.
solver = AsyncCapSkip(host="127.0.0.1", port=8080)

Yandex documents two ways to place the widget: a container with the class smart-captcha and a data-sitekey attribute, or a script that calls window.smartCaptcha.render with the key. The function below reads the attribute first. Then it falls back to the widget’s iframe, whose address carries the key as a sitekey query parameter according to the CapSkip docs, and waits up to ten seconds for it. I ran both routes against the mock. A key that lives only inside a script bundle has to be copied by hand.

async def find_sitekey(page):
    box = page.locator(".smart-captcha[data-sitekey]")
    if await box.count():
        return await box.first.get_attribute("data-sitekey")
    # Pages that draw the widget from script: read the iframe address.
    frame = page.locator("iframe[src*='sitekey=']").first
    await frame.wait_for(state="attached", timeout=10_000)
    query = urlsplit(await frame.get_attribute("src")).query
    return parse_qs(query)["sitekey"][0]

Step 2: ask for the token with the page’s own User-Agent

One awaited call does the work: await solver.yandex_smart(sitekey, url, **options) submits the task, polls CapSkip until the answer is ready and hands back a dictionary. There is no loop to write. Give url the page’s real address: Yandex matches a sitekey to the domain it runs on. The next block adds the wrapper.

async def get_token(page):
    sitekey = await find_sitekey(page)
    # The User-Agent the page itself reports is the one to hand over.
    user_agent = await page.evaluate("navigator.userAgent")
    result = await solver.yandex_smart(sitekey, page.url, userAgent=user_agent)
    return result["token"]

Against the mock the returned dictionary carried captchaId, code and token. The last two are one and the same string, the value for smart-token. Before anything is sent, the SDK refuses a sitekey that is not 16 to 120 letters, digits, underscores or hyphens, a page address that is not an absolute http or https URL, and any option the Yandex API does not take, such as action or invisible, by raising ValidationException. I fed it eleven bad calls, including a SOCKS4 proxy type, and the mock received no task from any of them. A sitekey of exactly 16 or 120 characters went through, and the ysc1_ prefix is not required.

With userAgent you choose the browser string CapSkip shows Yandex during the solve. I pass the one the page reports. A default headless Chromium reports HeadlessChrome there, and the mock saw HeadlessChrome/159.0.8154.6 in both the header and navigator.userAgent. The main function in Step 4 reads that string once and drops the word HeadlessChrome before building each context, so the header, the page and the solve agree. The default build’s Sec-CH-UA header still listed a HeadlessChrome brand, while the launch with channel set to chromium listed only Chromium, which is why Step 4 uses the channel.

What the mock can say about this is small. Its optional rule refuses a form post whose User-Agent differs from the one the task named, and a variant of the script with a different string hardcoded was refused three times out of three, while a variant with no userAgent option was accepted, because the mock then has nothing to compare. The mock cannot show that Yandex cares. The CapSkip docs say a current Chrome User-Agent is used when you send none. Note too that the token is minted in CapSkip’s own browser, not in yours.

Yandex solves use recaptchaTimeout, 300 seconds unless you change it, not defaultTimeout, which is 120. The source and a run agree: with defaultTimeout at 2 and recaptchaTimeout at 20, a mock token that took 6 seconds came back. The SDK checks the limit only before each poll, so a lower limit fires late. With recaptchaTimeout at 6 and a mock that never answered, TimeoutException arrived about 8.8 seconds after the call, because the polls came at roughly 0.2, 0.6, 1.2, 2.4 and 4.6 seconds and the sleep after the last one ran past the limit. The 15 to 30 seconds on the CapSkip Yandex page is CapSkip’s own estimate, and I could not time a real solve. For a hard budget, wrap the call in asyncio.wait_for: with a 2 second budget against a mock that never answered, it raised after 2.00 seconds and the polling stopped.

Yandex tokens last five minutes and can be checked once, per its docs. So solve after the page has loaded and the form is filled, then submit at once. Any wait of your own belongs before get_token.

Step 3: put the token into the form

The widget normally stores the token in a hidden input named smart-token inside its container. The block below fills that input, creates one in the form if the widget made none, and then calls the page’s own callback when the container has a data-callback attribute. Some pages keep the submit button disabled until it runs, as my mock page does, and without the call Playwright waits for a button that never turns on.

PUT_TOKEN = """(token) => {
  let field = document.querySelector('input[name="smart-token"]');
  if (!field) {
    field = document.createElement('input');
    field.type = 'hidden';
    field.name = 'smart-token';
    document.querySelector('form').appendChild(field);
  }
  field.value = token;
  const box = document.querySelector('.smart-captcha[data-callback]');
  const name = box && box.dataset.callback;
  if (name && typeof window[name] === 'function') {
    window[name](token);  // the page's own callback, if it has one
  }
}"""

The case this does not cover is a callback that the page registers through render() rather than an attribute. Its name is not on the page, so the function cannot find it. On my mock page of that kind the click waited 30 seconds, Playwright’s default, then failed, and no form post was made. Read the page’s script and call that function by name.

Step 4: sign up several accounts with one script

Append the last two blocks to yandex_signup.py, set SIGNUP_URL and run python yandex_signup.py [email protected] [email protected]. Every address gets its own browser context and its own sign-up. Your site needs these edits: the success text, shown as Account created, the captcha-refusal phrase, shown as Captcha check failed, the three selectors and YOUR_PASSWORD. Avoid the bare word captcha for the phrase, since any page carrying the widget would match it.

The retry rules follow the CapSkip docs. ERROR_CAPTCHA_UNSOLVABLE is answered by sending a new task, so the script does, though a changed replacement text for that error in CapSkip’s Settings would defeat the string check. A sitekey Yandex does not accept and a sitekey not allowed on the page’s domain would fail the same way again, so every other error ends that sign-up. A refused token is spent, so the script loads the page again and asks for a new one, three attempts at most.

async def signup(browser, user_agent, email, password):
    context = await browser.new_context(user_agent=user_agent)
    try:
        page = await context.new_page()
        for attempt in range(1, 4):
            await page.goto(SIGNUP_URL)
            await page.fill("input[name=email]", email)
            await page.fill("input[name=password]", password)
            try:
                token = await get_token(page)  # last step before the click
            except ApiException as err:
                if "ERROR_CAPTCHA_UNSOLVABLE" not in str(err):
                    raise  # a bad sitekey or domain would fail again
                print(f"{email} attempt {attempt}: unsolvable, new task")
                continue
            await page.evaluate(PUT_TOKEN, token)
            async with page.expect_navigation():
                await page.click("button[type=submit]")
            text = await page.inner_text("body")
            if "Account created" in text:  # your site's success text
                return text
            if "Captcha check failed" not in text:  # your site's phrase
                raise RuntimeError(f"{email}: refused, not by the captcha")
            print(f"{email} attempt {attempt}: token refused, new page")
        raise RuntimeError(f"{email}: no sign-up after 3 attempts")
    finally:
        await context.close()
async def main(emails):
    async with async_playwright() as p:
        # Headless. Pass headless=False as well to watch it work.
        browser = await p.chromium.launch(channel="chromium")
        probe = await browser.new_page()
        reported = await probe.evaluate("navigator.userAgent")
        await probe.close()
        # The headless build says HeadlessChrome. Present a normal Chrome.
        user_agent = reported.replace("HeadlessChrome", "Chrome")
        outcomes = await asyncio.gather(
            *(signup(browser, user_agent, e, "YOUR_PASSWORD") for e in emails),
            return_exceptions=True,
        )
        await browser.close()
    for email, outcome in zip(emails, outcomes):
        if isinstance(outcome, Exception):
            first = (str(outcome).splitlines() or [""])[0]
            outcome = f"{type(outcome).__name__}: {first}"
        print(email, "->", outcome[:60])


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1:] or ["[email protected]"]))

Why AsyncCapSkip here? Playwright’s async API runs on one event loop, and the plain CapSkip client sleeps between polls on that same thread, so while one account waits for its token every other page stands still. AsyncCapSkip awaits instead. I timed three accounts against a mock that took 3 seconds per token. The whole run took about 6 to 7.5 seconds with AsyncCapSkip and about 13 seconds with CapSkip (mock timings, Python 3.11.7, 3.13.7 and 3.14.0, with one outside run at 7.5 on 3.11.7). With one account the plain client finished first, 5.4 seconds against 6.5, so the async client buys nothing there. If you run many sign-ups, the parallel solving post shows how to cap the number at once.

I ran the finished script under all three Python versions against the mock, and each gave the same outcomes:

Mock settingWhat the script did
Container with data-sitekey, and a callback that enables the buttonOne task, the form post was accepted
Widget drawn by render(), key only in the iframe address, no callbackOne task, the key was read from the iframe, accepted
Widget script creates no hidden inputStep 3 created the field, one task, accepted
Widget script missing from the pageOne task, accepted
The poll answers ERROR_CAPTCHA_UNSOLVABLE twiceTwo retries, then the third token went through
The site turns down the first form post whatever it carriesThe script loaded the page again, took a second token, accepted. Two tasks
Poll answers an invalid sitekey or an invalid domain errorOne task, ApiException, and no form post was made
Site refuses a User-Agent that differs from the one in the task (variant with another string hardcoded)Three attempts all refused, then RuntimeError
Callback registered through render(), so the button stays disabledThe click timed out after 30 seconds. One task, no form post

Treat the rows as tests of my mock rather than of a live site. The five minute lifetime and the single use follow the Yandex docs, but the mock’s other rules are mine.

Common errors

The CapSkip codes come from the Yandex SmartCaptcha API docs, and I could not read them from a real app. The rows marked as seen are from my mock runs.

ErrorCauseFix
ValidationExceptionThe SDK rejected the arguments locally, before any request, for a reason listed in Step 2Read the message, which points at the argument
ERROR_RECAPTCHA_INVALID_SITEKEYYandex does not know this keyTake the key from the page again. Retrying is pointless, so the script stops
ERROR_RECAPTCHA_INVALID_DOMAINThe key belongs to other domains than the page you namedSend the URL the widget is served from
ERROR_CAPTCHA_UNSOLVABLEThe solve ended without a passSubmit a fresh task. The script allows three
ERROR_PROXY_CONNECT_REFUSEDCapSkip’s solve failed to connect to Yandex via your proxyCheck the proxy address and type, or send no proxy
ERROR_WRONG_USER_KEY or ERROR_KEY_DOES_NOT_EXISTThe app checks keys and the one sent is wrong. A client built without apiKey sends the key capskipCreate the client with your real key as apiKey
TimeoutExceptionNo token before recaptchaTimeout, 300 seconds unless you changed it, plus the last sleepOpen the Monitor tab in CapSkip to see the task, then rerun
NetworkExceptionNo listener on that host and port. Seen against a closed portRun CapSkip and set host and port to what its connection settings show
Playwright TimeoutError on the clickThe submit button is still disabled. Seen with a callback set through render()Call the page’s callback by name in Step 3
A site rejects a token you just fetchedThe token was used before, was older than five minutes or, where the site compares it, came with another User-AgentSend each token once, right after the solve, from the context that fetched the page

FAQ

Does CapSkip have to sit on the same PC as Playwright?

No, Server mode lets them sit apart. Turn it on in the connection settings of the CapSkip PC, as the setup guide explains, and give AsyncCapSkip that PC’s address as host. The script itself stays as it is. CapSkip then listens beyond 127.0.0.1 and leaves its port open to every address, so add a Windows Firewall block rule for every address except the machines you name. It is still your own hardware, with no metering.

Does my browser have to load the Yandex widget?

Not for the script. On the mock page, with the widget script blocked by context.route("**/captcha.js", lambda route: route.abort()), the sign-up still went through, because the data-sitekey attribute and the page’s own callback are still there. Step 3 then creates the field itself. Without the widget there is no iframe either, so the fallback in Step 1 finds nothing. I never loaded Yandex’s real widget, so I can’t say whether a real page copes with that.

How do I use a proxy for both the browser and the solve?

The two options have different shapes. The SDK takes proxy={"type": "HTTP", "uri": "login:password@IP:PORT"}, and the mock received it as a proxy and a proxy type. Playwright’s browser.new_context takes a proxy dictionary with server, username and password keys, per its network docs. I ran neither with a real proxy. The CapSkip docs say a same-address solve helps where a site checks the token’s origin IP, and the proxy guide covers choosing one.

The short version

Yandex SmartCaptcha in Python comes down to four moves: read the sitekey from the page, ask for a token with the page’s own User-Agent after the form is filled, write it into smart-token and click. CapSkip is a captcha bypass tool on a machine you own, so a token that gets refused adds nothing to a bill. The Python CAPTCHA solver page lists the SDK calls for other types, and the Playwright CAPTCHA solver page covers the browser side for them.