[Python] How to bypass HCaptcha using python selenium

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to automate a process on a website that uses hCaptcha by solving the captcha via an external API (SolveCaptcha) and injecting the token into the page using SeleniumBase. The API successfully returns a token and user-agent, but setting the token in the HTML doesn't seem to mark the captcha as solved, and form submission fails. I've tried setting the token in the h-captcha-response and g-recaptcha-response fields, as well as the data-hcaptcha-response attribute of the hCaptcha iframe, but it still doesn't work.

    Below is my Python code, which uses SeleniumBase to handle the browser and the SolveCaptcha API to get the token. I’ve also included the relevant HTML for the hCaptcha iframe.

    import time
    import json
    import requests
    from bs4 import BeautifulSoup
    from seleniumbase import SB
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait

    API_KEY = "KEY"
    PAGE_URL = "https://accounts.hcaptcha.com/demo"

    def solve_hcaptcha(sitekey):
    api_get_url = "https://api.solvecaptcha.com/res.php"
    api_post_url = "https://api.solvecaptcha.com/in.php"

    payload = {
    'key': API_KEY,
    'method': 'hcaptcha',
    'sitekey': sitekey,
    'pageurl': PAGE_URL,
    'json': 1
    }

    res = requests.post(api_post_url, data=payload)
    result: dict = res.json()

    if result.get("status") != 1:
    raise RuntimeError(f"Error sending request: {result.get('request')}")

    captcha_id = result.get("request")
    print("Received captcha_id:", captcha_id)

    while True:
    params = {
    'key': API_KEY,
    'action': 'get',
    'id': captcha_id,
    'json': 1
    }

    res = requests.get(api_get_url, params=params)
    data: dict = res.json()

    if data.get("status") == 1:
    print("Captcha solved successfully!")
    return data
    elif data.get("request") == "CAPCHA_NOT_READY":
    print("Captcha not ready yet, waiting 5 seconds...")
    time.sleep(5)
    else:
    raise RuntimeError(f"Error retrieving solution: {data.get('request')}")

    def set_captcha_token(sb, token: str):
    sb.execute_script(
    "document.querySelector(" + "'" + '[name="h-captcha-response"]' + "'" + ").innerHTML = " + "'" + token + "'")

    sb.execute_script(
    "document.querySelector(" + "'" + '[name="g-recaptcha-response"]' + "'" + ").innerHTML = " + "'" + token + "'")

    iframe = sb.find_element(By.CSS_SELECTOR, 'iframe[title="Widget containing checkbox for hCaptcha security challenge"]')
    sb.execute_script("arguments[0].setAttribute('data-hcaptcha-response', arguments[1])", iframe, token)

    def query_target_name(sb, first_name: str, middle_name: str, last_name: str):
    sb.type("//input[@id='id1']", 'aaron', By.XPATH)
    sb.type("//input[@id='ide']", 'marks', By.XPATH)
    sb.type("//input[@id='idf']", 'daniel', By.XPATH)

    sb.click("//input[@id='id3']", By.XPATH)

    wait = WebDriverWait(sb.driver, 10)
    wait.until(lambda driver: driver.current_url != PAGE_URL)


    def main():
    with SB(uc=True) as sb:
    sb.uc_open_with_reconnect(PAGE_URL, 10)

    try:
    sitekey = sb.get_attribute("div.h-captcha", "data-sitekey")
    print(f"Extracted sitekey: {sitekey}")
    except Exception as e:
    print(f"Failed to find element with data-sitekey: {e}")
    return

    try:
    solution = solve_hcaptcha(sitekey)
    token = solution.get("request")
    user_agent = solution.get("useragent")

    print("Token:", str(token))
    print("User-Agent:", user_agent)

    set_captcha_token(sb, str(token))
    print("Token successfully inserted into the form fields.")

    html = sb.get_page_source()
    with open("myhtml.html", 'w', encoding="utf-8") as file:
    file.write(html)

    query_target_name(sb, "Aaron", "Daniel", "Marks")
    print("Submitted target name to input box and pressed search")

    res = scrap_data_from_source(sb.get_page_source())
    print(res)

    time.sleep(10)
    except Exception as e:
    print(f"Failed to solve the captcha: {e}")
    return

    if __name__ == "__main__":
    main()


    Relevant HTML When I solve the hCaptcha manually, I see the token in the data-hcaptcha-response attribute of the iframe:

    <iframe
    src="https://newassets.hcaptcha.com/captcha/v1/.../static/hcaptcha.html#..."
    title="Widget containing checkbox for hCaptcha security challenge"
    data-hcaptcha-response="P1_eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..."
    style="pointer-events: auto; background-color: rgba(255, 255, 255, 0); border-radius: 4px; width: 302px; height: 76px; overflow: hidden;">
    </iframe>


    What I’ve Tried

    • Setting the Token: I’m setting the token in h-captcha-response and g-recaptcha-response fields using sb.execute_script and updating the iframe’s data-hcaptcha-response attribute.
    • Checking Elements: I noticed there’s no h-captcha-response textarea initially, so I set it via JavaScript. I suspect it needs to be created or waited for. User-Agent: The API returns a user-agent, but I’m not setting it in SeleniumBase, which might cause a mismatch.

    Any help or suggestions would be greatly appreciated! I’m using Python 3.9, SeleniumBase 4.x, and Chrome in undetected-chromedriver mode (uc=True). Additional Context

    The API (SolveCaptcha) works fine and returns a valid token and user-agent. The website is https://iapps.courts.state.ny.us/attorneyservices/search?0 for testing

    Continue reading...

Compartilhe esta Página