Recaptcha v2 Callback – Struggling with 2Captcha Solve

I am trying to solve a recaptcha v2 with callback, the recaptcha is the picture solving. I’m not entirely sure what my issue is because I only get hit with the recaptcha when I am in headless mode.

I am successfully extracting the Callback and sending with the solve. When this happens, the webpage advances to the next page. But the captcha window is still open. I am struggling to click the “verify” button -I am trying various methods to switch to the iframe but the “verify” button is not found- whether I use xpath, CSS etc

Can anyone help figure out where I am going wrong with this?

def solve_recaptcha(api_key, site_key, url):
    print(f"Sending sitekey to 2Captcha: {site_key}")
    # Send the sitekey to 2Captcha for solving
    response = requests.post(
        'http://2captcha.com/in.php',
        data={
            'key': api_key,
            'method': 'userrecaptcha',
            'googlekey': site_key,
            'pageurl': url
        }
    )
    print(f"2Captcha response: {response.text}")
    if response.text.startswith('OK|'):
        captcha_id = response.text.split('|')[1]
    else:
        raise Exception(f"Error from 2Captcha: {response.text}")

    # Retrieve the CAPTCHA solution
    while True:
        time.sleep(5)
        result = requests.get(f'http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}')
        if result.text == 'CAPCHA_NOT_READY':
            continue
        if result.text.startswith('OK|'):
            captcha_solution = result.text.split('|')[1]
            break
        else:
            raise Exception(f"Error from 2Captcha: {result.text}")

    print(f"CAPTCHA Solution: {captcha_solution}")
    return captcha_solution

try:


    # JavaScript function to find reCAPTCHA clients
    find_recaptcha_clients_js = """
    function findRecaptchaClients() {
      if (typeof (___grecaptcha_cfg) !== 'undefined') {
        return Object.entries(___grecaptcha_cfg.clients).map(([cid, client]) => {
          const data = { id: cid, version: cid >= 10000 ? 'V3' : 'V2' };
          const objects = Object.entries(client).filter(([_, value]) => value && typeof value === 'object');

          objects.forEach(([toplevelKey, toplevel]) => {
            const found = Object.entries(toplevel).find(([_, value]) => (
              value && typeof value === 'object' && 'sitekey' in value && 'size' in value
            ));

            if (typeof toplevel === 'object' && toplevel instanceof HTMLElement && toplevel['tagName'] === 'DIV'){
                data.pageurl = toplevel.baseURI;
            }

            if (found) {
              const [sublevelKey, sublevel] = found;

              data.sitekey = sublevel.sitekey;
              const callbackKey = data.version === 'V2' ? 'callback' : 'promise-callback';
              const callback = sublevel[callbackKey];
              if (!callback) {
                data.callback = null;
                data.function = null;
              } else {
                data.function = callback;
                const keys = [cid, toplevelKey, sublevelKey, callbackKey].map((key) => `['${key}']`).join('');
                data.callback = `___grecaptcha_cfg.clients${keys}`;
              }
            }
          });
          return data;
        });
      }
      return [];
    }
    return findRecaptchaClients();
    """

    # Execute the JavaScript function to get reCAPTCHA clients data
    recaptcha_data = driver.execute_script(find_recaptcha_clients_js)
    print(f"reCAPTCHA Data: {recaptcha_data}")

    if recaptcha_data:
        # Assuming the first reCAPTCHA client found is the target
        recaptcha_info = recaptcha_data[0]
        site_key = recaptcha_info['sitekey']
        callback_function = recaptcha_info.get('callback')

        # Solve the reCAPTCHA
        captcha_solution = solve_recaptcha(api_key, site_key, url)

        # Inject the solved token into the page
        driver.execute_script(f"document.getElementById('g-recaptcha-response').innerHTML='{captcha_solution}';")

        # Execute the callback function if it exists
        if callback_function:
            driver.execute_script(f"var callback = {callback_function}; callback('{captcha_solution}');")
        

        print("CAPTCHA solved and token submitted successfully.")
    else:
        print("No reCAPTCHA found on the page.")

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

I attaches some pics to show how the page is advancing after submitting solve [enter image description here](https://i.sstatic.net/TpprM7PJ.png)

As you can see, the page advances after submitting the solve, but iframe containing captcha is still present

Switching to iframe with

driver.switch_to.frame(0)
wait = WebDriverWait(driver, 10)
    button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[id*='verify']")))

    # Click the button
    button.click()
    print("Button clicked successfully!")

New contributor

Bob is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật