[英]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.