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

Selenium无法向YouTube搜索框发送输入的问题求助

解决Selenium操作YouTube搜索框时ElementNotInteractableException错误

问题原因

你定位的ytd-searchbox是搜索框的外层容器元素,而非实际接收输入的<input>标签。虽然点击容器能让搜索框高亮,但只有内部的input元素才能接受键盘输入,这就是调用send_keys时报错的核心原因。

解决方案

1. 定位正确的输入元素

可以通过以下几种方式定位实际的搜索输入框:

  • 使用CSS选择器:ytd-searchbox input,直接定位容器内的input子元素
  • 使用NAME属性:By.NAME, "search_query",这是YouTube搜索框原生的name属性
  • 使用ID属性:By.ID, "search",部分场景下该ID会生效

2. 等待元素可交互

将等待条件从presence_of_element_located替换为element_to_be_clickable,确保元素不仅存在于DOM中,还处于可交互状态。

修改后的代码示例

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
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
import time

service = Service(executable_path="chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("https://youtube.com")

# 等待搜索输入框可交互,使用CSS选择器定位实际input元素
input_element = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, "ytd-searchbox input"))
)

input_element.send_keys("some text" + Keys.ENTER)
time.sleep(10)
driver.quit()

额外说明

如果页面加载时出现YouTube的弹窗(比如Cookie同意提示),可能会遮挡搜索框导致无法交互,此时需要先处理弹窗,再进行搜索操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 14:56:03