gpt4 book ai didi

Python:Selenium "no such element"XPath 或 ID

转载 作者:行者123 更新时间:2023-12-01 07:38:19 26 4
gpt4 key购买 nike

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

我现在正在使用Selenium。我使用了两种方法将信息输入到字段中。一、使用 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)

关于Python:Selenium "no such element"XPath 或 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56860185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com