簡體   English   中英

selenium 無法使用 python 找到元素

[英]selenium cannot find element using python

這是我得到的 html,我正在嘗試 select 這個 fsuser 並使用 send_keys 輸入一些值。 我試過這個:

input_username = driver.find_element_by_xpath("//table/tbody/tr[2]/td/form/table/tbody/tr[1]/td[2]/input")

但是是說:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//table/tbody/tr[2]/td/form/table/tbody/tr[1]/td[2]/input"}
(Session info: chrome=99.0.4844.74)

HTML1 HTML2

可以直接使用name屬性,不需要絕對的xpath。

嘗試這個:

Css:

input[name='fsuser']

像這樣使用它:

input_username = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[name='fsuser']")))
input_username.send_keys('some name')

或者

xpath:

//input[@name='fsuser']

像這樣使用它:

input_username = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@name='fsuser']")))
input_username.send_keys('some name')

進口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

更新:

NoSuchElementException:

如果我們在HTML-DOM中有唯一條目,請檢查dev tools (Google chrome)。

您應該檢查的 xpath:

//input[@name='fsuser']

檢查步驟:

Press F12 in Chrome -> go 到element部分 -> 執行CTRL + F -> 然后粘貼xpath並查看你想要的element是否用1/1匹配節點突出顯示

如果這是唯一的//input[@name='fsuser']那么您還需要檢查以下條件。

  1. 檢查它是否在任何iframe/frame/frameset中。

    解決辦法:先切換到iframe/frame/frameset,再和這個web元素交互。

  2. 檢查它是否在任何shadow-root中。

    解決方法:使用driver.execute_script('return document.querySelector返回了一個web元素,然后進行相應的操作。

  3. 在與元素交互之前,請確保該元素已正確呈現。 設置一些hardcoded delayExplicit wait ,然后重試。

    解決方案: time.sleep(5)

    WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='vaadin-text-field-container']//descendant::input[@part='value' and starts-with(@aria-labelledby, 'vaadin-text-field-input')]"))).send_keys("test")

  4. 如果您已重定向到new tab/ or new windows並且您尚未切換到該特定new tab/new window ,否則您可能會遇到NoSuchElement異常。

    解決方案:先切換到相關窗口/標簽。

  5. 如果您已切換到 iframe 並且新的所需元素不在相同的 iframe 上下文中,則首先switch to default content然后與之交互。

    解決辦法:切換到默認內容,然后切換到各自的iframe。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM