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

时间:2020-04-23 08:01:45

标签: selenium selenium-webdriver xpath selenium-chromedriver

我正在尝试使用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)

1 个答案:

答案 0 :(得分:1)

正在回答以结束此问题。 正如Alok指出的那样,我们需要等待webelement完全加载后才能尝试对其进行访问。

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)
相关问题