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

Python Selenium调用Keys.RETURN提交搜索后未加载新页面怎么办

Selenium操作YouTube搜索不跳转修复方案

核心问题原因

  • 隐式等待仅校验元素是否存在于DOM树,不会校验元素是否处于可交互状态、对应的键盘提交事件是否绑定完成,操作过早会导致回车不生效
  • YouTube部分场景下搜索框的回车提交逻辑存在兼容性问题,直接触发点击搜索按钮更稳定
  • 旧版find_element_by_nameAPI在Selenium 4+中已废弃,可能出现定位不稳定的问题

修复后代码

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

driver = webdriver.Firefox()
driver.get("https://www.youtube.com/")
wait = WebDriverWait(driver, 15)

# 等待搜索框可交互后再操作
search_box = wait.until(EC.element_to_be_clickable((By.NAME, "search_query")))
search_box.clear()
search_box.send_keys("python")

# 二选一即可,优先选点击搜索按钮兼容性更高
# 方案1:回车提交
# search_box.send_keys(Keys.RETURN)
# 方案2:点击搜索按钮提交
search_btn = wait.until(EC.element_to_be_clickable((By.ID, "search-icon-legacy")))
search_btn.click()

修改说明

  • 引入显式等待判断元素可交互状态,确保操作时搜索框的所有事件绑定已经完成
  • 提供两种提交方式,优先选择点击搜索按钮的方案,不受页面键盘事件逻辑影响,稳定性更高
  • 替换为Selenium 4+官方推荐的定位写法,兼容新旧版本运行环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:57:02