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

Python和Selenium错误“;发生异常:NoTouchElementException“;,python,selenium,Python,Selenium,我正在使用Python语言中的Selenium库创建一个web自动化,但是当涉及用户名或电子邮件时,我会遇到这个错误(密码部分没有出现错误)。我在论坛上进行了研究,但没有找到解决方案。我是Python和selenium的新手,所以我在等待您的帮助 代码: 错误: Exception has occurred: NoSuchElementException Message: no such element: Unable to locate element: {"method"

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

代码:

错误:

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)
屏幕截图的代码:


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

是,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

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

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()。

抱歉,它给出了一个错误。代码#选择用户名WebDriverWait(浏览器,5)。直到(EC.frame_to_be_可用_和_switch_to_it((By.CSS_SELECTOR,.top)))时间。睡眠(5)错误:文件“C:\Users\User\AppData\Local\Programs\Python\Python36\lib\runpy.py”,第236行,在文件“C:\Python\protonmac.py”中,从文件Code=compile(f.read(),fname,'exec'))中获取代码,第40行WebDriverWait(浏览器,5)。直到(EC.frame_to_be_可用_和_switch_to_it((By.CSS_SELECTOR,.top)))^SyntaxError:EOL在扫描字符串literaloh时忘记关闭它。“.top”在我键入时有效。“.top”但在密码部分给出了相同的错误。我以前没有收到任何错误。相同的错误:发生了异常:NoSuchElementException消息:没有这样的元素:无法找到元素:{“方法”:“css选择器”,“选择器”:“[id=”password“]”}(会话信息:chrome=86.0.4240.75)非常感谢。我编写了代码,它很有效。作为一个例子,我编辑了这个主题。你能看一看吗?你认为有正确的代码吗?是的,它似乎是正确的。如果我的代码片段帮助了你,你可以将答案向上投票,这样也可以帮助其他人。
driver.switch_to.default_content()

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