[Python] Can't Submit Captcha While automating using python, playwright and 2captch

Discussão em 'Python' iniciado por Stack, Dezembro 21, 2024.

  1. Stack

    Stack Membro Participativo

    im working on project which automates the suno.com which includes signup/login, entering prompt and generating song, but as soons as i click on generate/create button it shows me captcha. so to solve that captcha im using 2captcha, once i recieve token from 2captcha i insert it into iframe data-hcaptcha-response, i tried inserting it into text area h-captcha-response, script successfully inserts the token but im not able to submit the captcha as it's skip captcha button remains as it is, it doesnt change to verify or submit.

    these are image captcha which tells to identify same images as shown in, or find images with square inside triangle like that.

    here is the solve captcha function which handles captcha in my code:

    async def solve_hcaptcha(page, url, site_key):
    """
    Solve hCaptcha using 2Captcha and inject the response into the iframe
    """
    try:
    print("Starting hCaptcha solving process...")
    print(f"Using site key: {site_key}")
    print(f"Page URL: {url}")

    # Check if hCaptcha iframe is present
    hcaptcha_frame = await page.query_selector('iframe[data-hcaptcha-widget-id]')
    if hcaptcha_frame:
    print("✓ hCaptcha iframe detected on the page")
    frame_src = await hcaptcha_frame.get_attribute('src')
    print(f"Frame source: {frame_src}")
    else:
    print("⚠ No hCaptcha iframe found on the page")
    return False

    # Initialize 2Captcha solver
    print("Initializing 2Captcha solver...")
    solver = TwoCaptcha("api_key")
    print("✓ 2Captcha solver initialized")

    try:
    print("Sending solve request to 2Captcha API...")
    result = solver.hcaptcha(
    sitekey=site_key,
    url=url
    )
    print("✓ Received response from 2Captcha API")

    token = result.get('code')
    if not token:
    print("⚠ Failed to solve hCaptcha: No token received")
    return False

    print("✓ Successfully received captcha token")
    print(f"Token (first 30 chars): {token[:30]}...")

    # Updated token injection approach targeting the iframe
    inject_script = f"""
    (() => {{
    const iframe = document.querySelector('iframe[data-hcaptcha-widget-id]');
    if (iframe) {{
    iframe.setAttribute('data-hcaptcha-response', '{token}');

    // Create and dispatch a custom event to notify any listeners
    const event = new CustomEvent('hcaptcha-response', {{
    detail: {{ response: '{token}' }},
    bubbles: true
    }});
    iframe.dispatchEvent(event);

    return true;
    }}
    return false;
    }})()
    """

    injection_result = await page.evaluate(inject_script)
    print(f"✓ Token injection result: {injection_result}")

    # Wait for any potential processing
    await page.wait_for_timeout(2000)

    # Try to find and click verify button if present
    verify_button_selectors = [
    'iframe[data-hcaptcha-widget-id]', # Try clicking the iframe itself first
    'div.button-submit.button[role="button"][title="Verify Answers"]',
    '.h-captcha-submit-button',
    'button[type="submit"]',
    '[id^="anchor-"]'
    ]

    for selector in verify_button_selectors:
    try:
    button = page.locator(selector)
    if await button.count() > 0:
    print(f"✓ Found verify button with selector: {selector}")
    await button.first.click()
    print("✓ Clicked verify button")
    await page.wait_for_timeout(2000)
    break
    except Exception as e:
    print(f"⚠ Could not click button with selector {selector}: {e}")

    print("hCaptcha solving process completed")
    return True

    except Exception as e:
    print(f"⚠ Error during captcha solving: {str(e)}")
    return False

    except Exception as e:
    print(f"⚠ Unexpected error in captcha solving: {str(e)}")
    return False


    async def handle_cloudflare_verification(page):
    try:
    # First check if hCaptcha iframe exists
    hcaptcha_frame = await page.query_selector('iframe[src*="hcaptcha"]')
    if not hcaptcha_frame:
    print("No hCaptcha detected on the page")
    return

    # Extract site key from the iframe src
    frame_src = await hcaptcha_frame.get_attribute('src')
    site_key_match = re.search(r'sitekey=([^&]+)', frame_src)

    if site_key_match:
    site_key = site_key_match.group(1)
    print(f"Found site key: {site_key}")
    else:
    site_key = SITE_KEY
    print(f"Using default site key: {site_key}")

    # Solve the hCaptcha
    success = await solve_hcaptcha(page, page.url, site_key)

    if success:
    print("CAPTCHA verification completed successfully.")
    await page.wait_for_timeout(3000)
    else:
    print("CAPTCHA verification failed.")

    except Exception as e:
    print(f"Error during CAPTCHA handling: {e}")


    also when i tried to remove the display:none coode from css it doenst really showed text area, i mean it wasnt visible. if you try same on https://www.google.com/recaptcha/api2/demo you can see the text area.

    Continue reading...

Compartilhe esta Página