簡體   English   中英

Selenium 4 找不到元素

[英]Selenium 4 can't find the element

我正在使用 selenium python 創建 rambler autoreg 郵件,遇到了一個問題,即 selenium can't find the item ,盡管它在那里。 從錯誤中可以清楚地看出 selenium 無法找到該項目(最底部的錯誤文本)。 一直在尋找解決方案,但它們大多與另一個問題有關,請幫助您,在此先感謝。

HTML

...
<footer class = "styles_popupFooter__1pUND" ...>
    <div class="styles_footer__wCsAz rui-Typography-reset rui-Typography-text">
        <a class="styles_link___lR7s styles_link__lCdad" ... >Registration<a>
        ...
    <div>
    ...
<footer>
    ...

Python

# Selenium 4
from selenium import webdriver
from selenium.webdriver.firefox.service import Service

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

class GenerateEmail:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, 30)

    def main(self):
        url = "https://mail.rambler.ru/?utm_source=head&utm_campaign=self_promo&utm_medium=header&utm_content=mail"
        self.driver.get(url)

        value = '//div[@class="styles_footer__wCsAz rui-Typography-reset rui-Typography-text"]//a[text()="Registration"]'
        self.wait.until(EC.element_to_be_clickable((By.XPATH, value)))
        button = self.driver.find_element(by=By.XPATH, value=value)
        button.click()

def start():
    try:
        s = Service(executable_path='driver/geckodriver.exe')
        driver = webdriver.Firefox(service=s)

        g_email = GenerateEmail(driver)
        g_email.main()
    except Exception as e:
        print(e)
    finally:
        driver.close()

if __name__ == '__main__':
    start()

錯誤

Message:
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:186:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:398:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16

您要Registration的元素位於iframe中,您需要先切換它才能訪問該元素。 使用Webdriverwait()frame_to_be_available_and_switch_to_it()

  def main(self):
        url = "https://mail.rambler.ru/?utm_source=head&utm_campaign=self_promo&utm_medium=header&utm_content=mail"
        self.driver.get(url)
        
        self.wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//div[@data-id-frame='embed']//iframe")))

        value = '//div[@class="styles_footer__wCsAz rui-Typography-reset rui-Typography-text"]//a[text()="Registration"]'
        self.wait.until(EC.element_to_be_clickable((By.XPATH, value)))
        button = self.driver.find_element(by=By.XPATH, value=value)
        button.click()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM