我想用python(3.7.3)写一个脚本,第一次使用Selenium自动登录网站。我用一些基本的例子进行了练习,并查看了Selenium文档。到目前为止,一切都很好。但当我在自己选择的网站上尝试时,事情却出了问题......
我设法打开了登录页面,但是每当我试图获取用户名字段对应的元素ID时,我得到的是 "NoSuchElementException",表明我使用的ID-name应该是不正确的。我是通过在用户名框中右击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知识几乎是不存在的,这可能对我没有帮助。
EDIT 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所指出的,我们需要等待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)