繁体   English   中英

Python:Selenium“没有这样的元素”XPath 或 ID

[英]Python: Selenium "no such element" XPath or ID

我正在尝试登录 Tessco.com 我了解到该站点使用 JavaScript,这就是我无法使用 RoboBrowser 找到表单的原因。

我现在正在使用硒。 我使用了两种方法在字段中输入信息。 一、使用driver.find_element_by_xpath()以及driver.find_element_by_id()

两次尝试都会产生错误。 代码如下:

import time
from selenium import webdriver
chrome_path = r"C:\Users\James\Documents\Python Scripts\jupyterNoteBooks\ScrapingData\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.tessco.com/login")

userName = "FirstName.SurName321123@gmail.com"
password = "PasswordForThis123"

elem = driver.find_element_by_xpath("""//*[@id="userID"]""")
elem = send_keys(userName)

elem = driver.find_element_by_xpath("""//*[@id="password"]""")
elem = send_keys(password)

driver.close()

错误是:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="userID"]"}

当我使用 ID 调用元素时:

elem = driver.find_element_by_id("userID")
elem = send_keys(userName)

elem = driver.find_element_by_id("password")
elem = send_keys(password)

我得到:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="userID"]"}

我的印象是我检查了元素并使用了适当的名称。

我没有正确做的任何提示或想法?






下面评论部分提供了解决方案。 代码修改为:

import time
from selenium import webdriver
#Webdriver wait functions being introduced to add a delay.
#I was running into problems, with the ID not being found
#add wait for the element to be clickable before trying send keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

chrome_path = r"C:\Users\James\Documents\Python Scripts\jupyterNoteBooks\ScrapingData\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://www.tessco.com/login")

userName = "FirstName.SurName321123@gmail.com"
password = "PasswordForThis123"

wait = WebDriverWait(driver, 10)

elem = wait.until(EC.element_to_be_clickable((By.ID, "userID"))) 
elem.send_keys(userName)

elem = wait.until(EC.element_to_be_clickable((By.ID, "password"))) 
elem.send_keys(password)

driver.close()

该元素最初可能不可见,这可能会导致失败。 等到元素可见/可点击,然后使用发送键。

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "userID"))).send_keys(userName)

我猜元素搜索发生在它加载之前。 我的建议是尝试等待一段时间,它应该会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM