[英]Cannot find the css selector, method or element error using Selenium and 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)
可以直接使用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']
那么您還需要檢查以下條件。
檢查它是否在任何iframe/frame/frameset
中。
解決辦法:先切換到iframe/frame/frameset,再和這個web元素交互。
檢查它是否在任何shadow-root
中。
解決方法:使用driver.execute_script('return document.querySelector
返回了一個web元素,然后進行相應的操作。
在與元素交互之前,請確保該元素已正確呈現。 設置一些hardcoded delay
或Explicit 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")
如果您已重定向到new tab/ or new windows
並且您尚未切換到該特定new tab/new window
,否則您可能會遇到NoSuchElement
異常。
解決方案:先切換到相關窗口/標簽。
如果您已切換到 iframe 並且新的所需元素不在相同的 iframe 上下文中,則首先switch to default content
然后與之交互。
解決辦法:切換到默認內容,然后切換到各自的iframe。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.