硒无法通过ID或xpath找到元素

固铂

我正在尝试在python(3.7.3)中编写一个脚本,以通过首次使用Selenium自动登录网站。我练习了一些基本示例,并浏览了Selenium文档。到目前为止一切都很好。但是当我在自己选择的网站上尝试时;事情出了问题...

我正在设法打开登录页面,但是每当我尝试获取与用户名字段相对应的元素ID时,我都会得到“ NoSuchElementException”,这表明我使用的ID名称被认为是错误的。我通过右键单击用户名框中的HTML代码并使用检查功能来获得名称。当这不起作用时,我试图通过xpath找到它,但是也没有成功。谁能指出为什么该元素未被识别?

Python代码

from selenium import webdriver

path = r"C:\Users\path\chromedriver.exe"
driver = webdriver.Chrome(path)

driver.get ("https://a website")
driver.find_element_by_id("login-username").send_keys(login)
driver.find_element_by_id("login-sign-in-button").click()

错误信息

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="login-username"]"}

用户名字段的HTML代码:

<input id="login-username" type="text" name="username" placeholder="Username" msd-placeholder="Username" class="margin-bottom form-control ng-pristine ng-empty ng-invalid ng-invalid-required ng-touched" ng-model="formData.username" dh-autofocus="" required="">

寻找与xpath的元素。为了避免错误,我将ID周围的“”括号改为“”。

driver.find_element_by_xpath("//*[@id='login-username']").send_keys(login)

最后我尝试了长的xpath

driver.find_element_by_xpath("/html/body/ui-view/ui-view/div/div[1]/div[1]/ui-view/div/div[1]/div/div[2]/form/div[1]/div/input").send_keys(login)

老实说,我在这里撞墙。可能对我几乎不存在的HTML知识没有帮助。

编辑1添加了等待功能。代码现在可以使用

driver.get ("https://a website")
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "login-username")))
driver.find_element_by_id("login-username").send_keys(login)
固铂

回答以关闭此问题。正如Alok指出的那样,我们需要等待Web元素完全加载后才能尝试访问它。

driver.get ("https://a website")
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "login-username")))
driver.find_element_by_id("login-username").send_keys(login)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章