selenium xpath 的 Chropath 不起作用?

Chropath for selenium xpath is not working?

我安装了 chropath 来找出网站的 xpath。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome("C:\Users\ADMIN\Downloads\chromedriver_win32\chromedriver.exe")

driver.get("https://kite.zerodha.com")

username = driver.find_element_by_xpath("//input[@placeholder='User ID']")
username.send_keys("abcc")

我想使用 chropath 查找用户名 xpath,它给了我 //input[@placeholder='User ID'] 但它仍然给我 NoSuchElementException 错误。我认为 chropath 扩展总是会给我正确的 xpath。 这可能是什么原因?

这是我检查用户名时得到的代码

<input type="text" placeholder="User ID" autocorrect="off" maxlength="6" autofocus="autofocus" autocapitalize="characters" animate="true" label="" rules="[object Object]" dynamicwidthsize="8" xpath="1">

我检查了您的代码,我认为它是正确的,但是,我认为您可能缺少 .click() 元素。为确保元素存在,您可以执行以下操作,我在其中添加了可选的元素加载等待时间。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Handle wait time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

driver = webdriver.Chrome("C:\Users\ADMIN\Downloads\chromedriver_win32\chromedriver.exe")

driver.get("https://kite.zerodha.com")

wait = WebDriverWait(driver, 60)

username = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@placeholder='User ID']")))
username.click()
username.send_keys("abcc")

功能上, was correct to find the for the desired element. However as the element is having the attribute animate="true", when the element recieves the cursor focus the attribute placeholder="User ID" gets changed as a result 无法定位元素。


解决方案

要在 用户 ID 字段中发送 字符序列,您必须引入 WebDriverWait对于 element_to_be_clickable(),您可以使用以下任一项 :

  • 使用XPATH:

    driver.get('https://kite.zerodha.com/')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//label[text()='User ID']//following-sibling::input[1]"))).send_keys("TANMAY")
    
  • 使用CSS_SELECTOR:

    driver.get('https://kite.zerodha.com/')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "label.su-input-label.su-dynamic-label + input"))).send_keys("TANMAY")
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照: