raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: #loginUsername
我使用硒模块来自动化一些网站的登录过程,当我执行程序时,它抛出NoSuchElementException
,而我尝试了所有的find_element_by_*
方法(通过id,通过类,通过css选择器,通过文本,通过名称attr),但是,我仍然得到这个错误,我不知道如何使这个程序无错误,所以,有没有其他方法来调试程序?
我没有足够的声誉来评论,所以发表了一个答案。我认为下列任何一种原因都可能是原因。
-
请检查元素
xPath
id
等在铬控制台,以确保您使用正确的locator
-
没有足够的时间让元素可访问。请使用
explicit
等待。 -
可能是元素是
present
在DOM上,但不是visible
当你试图执行操作。 -
从错误信息中我可以看到你正在使用
css
选择器#loginUsername
。我想你没有给tag
的名字就像它应该是input#loginUsername
我理解你上面所说的没有iframe。
确保在调用find_element(…)之前等待元素被加载并可用。
像这样做:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome("D:/chromedriver/94/chromedriver.exe")
driver.get("https://yourwebsite.com")
# use By.XPATH, By.CLASS_NAME etc. depending on the
# element you're referring to
WebDriverWait(driver, 60).until(EC.presence_of_element_located((By.ID, 'loginUsername')))
login = driver.find_element(By.ID, 'loginUsername')