我正在嘗試學習 selenium,但我偶然發現了一個我似乎無法修復的錯誤:ElementNotInteractableException(代碼給出了超時例外)。我已經閱讀了各種 stackoverflow 帖子并嘗試了答案,但都沒有奏效。我只是想在 Youtube 的搜索欄中輸入幾個詞。無論如何,這是代碼。
import undetected_chromedriver.v2 as uc
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
options = uc.ChromeOptions()
options.binary_location = "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
options.add_argument("--user-data-dir=c:\\temp\\testprofile2")
driver = uc.Chrome(options=options)
driver.get("https://www.youtube.com/")
def enter_search_term(driver):
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="search"]'))).send_keys("test")
time.sleep(5)
driver.quit()
enter_search_term(driver)
uj5u.com熱心網友回復:
問題的原因可能是,您嘗試發送鍵的元素不是應該接收輸入文本的真實元素。
1 確保由 找到單個元素'//*[@id="search"]'。(如果有多個,您的腳本將與第一個找到的可能隱藏的互動)。
2 確保搜索欄位未隱藏,具有正的寬度和高度。
如果您有一些 selenium 錄音播放工具,例如 selenium IDE,您可以嘗試在啟用錄音的情況下手動執行所有步驟,這樣您將在輸出腳本中看到接收搜索文本的真實元素。
也試著看看這篇文章
那么你可以使用下面的XPath
//input[@id='search']
所以你的有效代碼將是:
options = uc.ChromeOptions()
options.binary_location = "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
options.add_argument("--user-data-dir=c:\\temp\\testprofile2")
driver = uc.Chrome(options=options)
driver.maximize_window()
driver.get("https://www.youtube.com/")
def enter_search_term(driver):
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@id='search']"))).send_keys("test")
time.sleep(5)
driver.quit()
enter_search_term(driver)
我已經測驗過了,它作業正常。請注意,我也在最大化瀏覽器。并使用visibility_of_element_located
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/381179.html
