Задать вопрос
mimiseksimi
@mimiseksimi

Как решить проблему с автоматическим решением капчи в selenium?

Я пытаюсь автоматизировать создание учетной записи, и у меня возникли проблемы с поиском hcaptcha, я не могу понять, в чем проблема, уже несколько дней.

HTML форма

<div class="focusLock__28507" role="dialog" aria-label="CAPTCHA" tabindex="-1" aria-modal="true">
    <div class="modal__1237a root_a28985 small_f8e677 fullscreenOnMobile__05784 rootWithShadow_d20cd6" style="opacity: 1; transform: scale(1);">
        <div class="content_b28aab container__73ab0 thin__62e51 scrollerBase__65223" dir="ltr" style="overflow: hidden scroll; padding-right: 8px;">
            <button aria-label="Close" type="button" class="close_c16dd6 close__1080c button__581d0 lookBlank_a5b4ca colorBrand__27d57 grow__4c8a4">
                <div class="contents__322f4">
                    <svg aria-hidden="true" role="img" class="closeIcon__16020" width="24" height="24" viewBox="0 0 24 24">
                        <path fill="currentColor" d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z"></path>
                    </svg>
                </div>
            </button>
            <div class="content_ab6500">
                <div><img src="/assets/b988a7c400d2fd2b7e5b.svg" alt=""></div>
                <div class="title__1bf8a" aria-hidden="true">Wait! Are you human?</div>
                <div>Confirm that you are not a robot.</div>
                <div class="captchaContainer_c3b486">
                    <div>
                        <iframe src="https://newassets.hcaptcha.com/captcha/v1/344795b/static/hcaptcha.html#frame=checkbox&amp;id=01b54n9vmua1&amp;host=discord.com&amp;sentry=true&amp;reportapi=https%3A%2F%2Faccounts.hcaptcha.com&amp;recaptchacompat=true&amp;custom=false&amp;hl=ru&amp;tplinks=on&amp;pstissuer=https%3A%2F%2Fpst-issuer.hcaptcha.com&amp;sitekey=4c672d35-0701-42b2-88c3-78380b0db560&amp;theme=light&amp;origin=https%3A%2F%2Fdiscord.com"
                        tabindex="0" frameborder="0" scrolling="no" allow="private-state-token-issuance 'src'; private-state-token-redemption 'src'" title="A checkbox widget for hCaptcha security checks" data-hcaptcha-widget-id="01b54n9vmua1" data-hcaptcha-response=""
                        style="pointer-events: auto; width: 303px; height: 78px; overflow: hidden;"></iframe>
                        <textarea id="g-recaptcha-response-01b54n9vmua1" name="g-recaptcha-response" style="display: none;"></textarea>
                        <textarea id="h-captcha-response-01b54n9vmua1" name="h-captcha-response" style="display: none;"></textarea>
                    </div>
                </div>
            </div>
            <div aria-hidden="true" style="position: absolute; pointer-events: none; min-height: 0px; min-width: 1px; flex: 0 0 auto; height: 0px;"></div>
        </div>
    </div>
</div>



Мой код

def create_account(email, email_password):
    def enter_username(username):
        username_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'username')))
        username_input.clear()
        username_input.send_keys(username)
        driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click()
        time.sleep(3)

    username = get_random_username()
    display_name = f"{username}_{random.randint(100, 999)}"
    password = email_password
    birth_day = str(random.randint(1, 28))
    birth_month = random.choice([
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ])
    birth_year = str(random.randint(1993, 2003))

    driver.get('https://discord.com/register')

    email_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'email')))
    email_input.send_keys(email)
    
    display_name_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'global_name')))
    display_name_input.send_keys(display_name)
    
    password_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, 'password')))
    password_input.send_keys(password)

    birth_day_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="day__86dab"]//input[@aria-label="День"]')))
    birth_day_input.send_keys(birth_day)

    birth_month_dropdown = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="month_c81b3d"]')))
    birth_month_dropdown.click()
    birth_month_option = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, f'//div[contains(text(), "{birth_month.lower()}")]')))
    birth_month_option.click()

    birth_year_input = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="year__37788"]//input[@aria-label="Год"]')))
    birth_year_input.send_keys(birth_year)

    checkbox = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.checkbox_fcf2ad.box__66058')))
    driver.execute_script("arguments[0].click();", checkbox)
    
    enter_username(username)

    while driver.find_elements(By.CSS_SELECTOR, 'span.errorMessage_a5e469'):
        username = get_random_username()
        enter_username(username)

    if driver.find_elements(By.CSS_SELECTOR, 'div.captchaContainer_c3b486 iframe'):
        hcaptcha_iframe = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.captchaContainer_c3b486 iframe')))
        driver.switch_to.frame(hcaptcha_iframe)

        site_key = hcaptcha_iframe.get_attribute('src').split('sitekey=')[1].split('&')[0]
        driver.switch_to.default_content()

        hcaptcha_response = solve_hcaptcha(site_key, driver.current_url)
        
        driver.execute_script("document.getElementsByName('h-captcha-response')[0].style.display = 'block';")
        driver.execute_script(f"document.getElementsByName('h-captcha-response')[0].innerHTML = '{hcaptcha_response}';")
        driver.execute_script("document.getElementsByName('g-recaptcha-response')[0].style.display = 'block';")
        driver.execute_script(f"document.getElementsByName('g-recaptcha-response')[0].innerHTML = '{hcaptcha_response}';")

        driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]').click()
    
    time.sleep(5)



Моя ошибка

Traceback (most recent call last):
  File "C:\Users\tishk\Downloads\discord\main.py", line 226, in <module>
    result = create_account(email, email_password)
  File "C:\Users\tishk\Downloads\discord\main.py", line 165, in create_account
    site_key = hcaptcha_iframe.get_attribute('src').split('sitekey=')[1].split('&')[0]
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 178, in get_attribute
    attribute_value = self.parent.execute_script(
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 407, in execute_script
    return self.execute(command, {"script": script, "args": converted_args})["value"]
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 347, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found
  (Session info: chrome=120.0.6099.130); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#stale-element-reference-exception
Stacktrace:
    GetHandleVerifier [0x00007FF762252142+3514994]
    (No symbol) [0x00007FF761E70CE2]
    (No symbol) [0x00007FF761D176AA]
    (No symbol) [0x00007FF761D279BF]
    (No symbol) [0x00007FF761D1DB89]
    (No symbol) [0x00007FF761D1DC93]
    (No symbol) [0x00007FF761D1BF22]
    (No symbol) [0x00007FF761D1F6F7]
    (No symbol) [0x00007FF761D1F5A2]
    (No symbol) [0x00007FF761DA316B]
    (No symbol) [0x00007FF761D85FEA]
    (No symbol) [0x00007FF761DA28F6]
    (No symbol) [0x00007FF761D85D93]
    (No symbol) [0x00007FF761D54BDC]
    (No symbol) [0x00007FF761D55C64]
    GetHandleVerifier [0x00007FF76227E16B+3695259]
    GetHandleVerifier [0x00007FF7622D6737+4057191]
    GetHandleVerifier [0x00007FF7622CE4E3+4023827]
    GetHandleVerifier [0x00007FF761FA04F9+689705]
    (No symbol) [0x00007FF761E7C048]
    (No symbol) [0x00007FF761E78044]
    (No symbol) [0x00007FF761E781C9]
    (No symbol) [0x00007FF761E688C4]
    BaseThreadInitThunk [0x00007FFCFEA47614+20]
    RtlUserThreadStart [0x00007FFCFEB826F1+33]

  • Вопрос задан
  • 132 просмотра
Подписаться 1 Средний 6 комментариев
Решения вопроса 1
Mike_Ro
@Mike_Ro Куратор тега Python
Python, JS, WordPress, SEO, Bots, Adversting
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found
(Session info: chrome=120.0.6099.130); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/t...

Изучаем ссылку, скорее всего, либо обновление dom, либо неправильная работа с контекстом. Чтобы понять, что dom изменился - достаточно получить элемент еще раз, тут проблем нет, а вот с контекстом интереснее:
if driver.find_elements(By.CSS_SELECTOR, 'div.captchaContainer_c3b486 iframe'):
    hcaptcha_iframe = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'div.captchaContainer_c3b486 iframe')))

    # Переключили контекст на фрейм.
    driver.switch_to.frame(hcaptcha_iframe)

    # Не верно! Мы сменили контекст на hcaptcha_iframe,
    # в нашем новом контексте нет элемента, на который ссылается hcaptcha_iframe,
    # а значит, оптимальнее обратиться к driver.
    #
    # site_key = hcaptcha_iframe.get_attribute('src').split('sitekey=')[1].split('&')[0]

    # Вот теперь правильно.
    site_key = driver.find_element(By.TAG_NAME, 'iframe').get_attribute('src').split('sitekey=')[1].split('&')[0]

    driver.switch_to.default_content()
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы