Python和Selenium错误“发生异常:NoTouchElementException”

2024-06-15 01:03:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python语言中的Selenium库创建一个web自动化,但是当涉及用户名或电子邮件时,我会遇到这个错误(密码部分没有出现错误)。我在论坛上进行了研究,但没有找到解决方案。我是Python和selenium的新手,所以我在等待您的帮助

代码:

#Get Url
browser.get('https://mail.protonmail.com/create/new?language=en')
time.sleep(5)

#Choose Username 
browser.find_element_by_id('username').send_keys('usernameForUser')
time.sleep(5)

错误:

Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}

(Session info: chrome=86.0.4240.75)

屏幕截图的代码:

enter image description here

Div中出现了一个iframe代码。问题是否由此引起


Tags: 代码browserweb语言idtimeselenium错误
2条回答

用户名文本框位于框架内,因此要与之交互,您需要切换框架

frames = driver.find_elements_by_tag_name("iframe")
print(len(frames))

driver.switch_to.frame(0)
wait = WebDriverWait(driver, 20)
username = wait.until(EC.presence_of_element_located((By.ID, "username")))
username.send_keys("xyz")

密码文本框不在框架中,因此您必须将控件切换回主页面并超出密码文本框。由于密码文本框在从帧切换后需要一些时间来准备访问,所以在此处使用显式等待。像

driver.switch_to.default_content()

password = wait.until(EC.presence_of_element_located((By.ID, "password")))
password.send_keys("123")

还有一件事,因为加载URL需要时间,所以使用隐式等待而不是time.sleep()

是,iframe需要切换到

WebDriverWait(browser, 5).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, '.top')))

进口

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

相关问题 更多 >