You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium向YouTube搜索框输入内容时遇element not interactable错误

问题原因及解决办法

出现element not interactable报错,主要有这几个原因,对应解决方式如下:

  • 元素定位错误
    你用//*[@id="search-input"]定位到的是搜索框的外层容器div,不是真正能输入文本的input元素。YouTube实际可输入的搜索框ID是search,正确的定位可以用By.ID, "search"或者对应的XPath//input[@id="search"]。

  • 页面未加载完成就执行操作
    Selenium打开页面后,可能搜索框还没完全渲染出来就执行了输入操作,这时候元素虽然存在但不可交互。需要添加显式等待,等元素可以被点击交互后再操作。

  • Cookie弹窗遮挡干扰
    部分地区打开YouTube会弹出Cookie同意窗口,这个弹窗可能会遮挡搜索框,或者导致页面元素状态异常,影响后续交互。需要先关闭这个弹窗。

修正后的代码示例

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

PATH = "C:\\Program Files (x86)\\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://youtube.com")

try:
    # 等待Cookie弹窗并关闭(如果出现)
    cookie_agree_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//button[@aria-label="同意"]'))
    )
    cookie_agree_btn.click()
    
    # 等待搜索框可交互,使用正确的定位
    searchbox = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "search"))
    )
    searchbox.send_keys('Jack West')
    # 可选:按下回车执行搜索
    searchbox.send_keys(Keys.ENTER)
finally:
    # 按需关闭浏览器,比如 driver.quit()
    pass

内容的提问来源于stack exchange,提问作者joshuadiep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:50:24