繁体   English   中英

selenium-python 无法定位元素

[英]selenium-python cannot locate element

我需要在garmin connect 网站上输入凭据。 我使用 python 3.10 和 chrome=108.0.5359.94。

用户名元素代码:

<input class="login_email" name="username" id="username" value="" type="email" spellcheck="false" autocorrect="off" autocapitalize="off" aria-required="true">

我尝试了以下内容:

browser.maximize_window()
browser.implicitly_wait(3)

browser.find_element(By.ID, "username")
browser.find_element(By.CLASS_NAME, 'input#username.login_email')
browser.find_element(By.CLASS_NAME, 'login_email')
browser.find_element(By.XPATH, '/html/body/div/div/div[1]/form/div[2]/input')
browser.find_element(By.XPATH, '//*[@id="username"]')

我收到以下错误:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: 

我搜索了一些信息,有人说这可能是由于 shadow dom。 但我认为这不是我的情况,因为我在 html 结构中看不到shadow-smth 有任何想法吗?

登录表单位于 iframe 中。因此,要访问其中的元素,您首先需要切换到 iframe。
以下代码有效:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
wait = WebDriverWait(driver, 20)

url = "https://connect.garmin.com/signin/"

driver.get(url)

wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))

wait.until(EC.element_to_be_clickable((By.ID, "username"))).send_keys("my_name")
wait.until(EC.element_to_be_clickable((By.ID, "password"))).send_keys("my_password")

结果是

在此处输入图像描述

在 iframe 内部完成工作后,不要忘记切换到默认内容

driver.switch_to.default_content()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM