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
相关产品推荐
相关产品推荐

