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

使用Selenium在Google Finance搜股票遇ElementNotInteractableException错误求助

解决Google Finance搜索时的ElementNotInteractableException问题

核心原因

出现ElementNotInteractableException通常是因为:

  • 定位到的元素尚未完全加载完成,不具备交互条件
  • 使用了不稳定的动态类名(Google页面的类名经常会更新)
  • 输入框未被激活,无法接收键盘输入
  • 页面弹窗(如Cookie同意提示)遮挡了目标元素

解决方案

1. 替换为稳定选择器+显式等待

Google Finance的搜索框可以通过placeholder属性或更稳定的DOM结构定位,避免依赖易变的类名。同时使用WebDriverWait等待元素可交互,替代不可靠的time.sleep。

修改后的代码:

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

driver = webdriver.Chrome()
url = 'https://www.google.com/finance/'
driver.get(url)

# 等待搜索框可交互,通过placeholder属性定位
wait = WebDriverWait(driver, 10)
input_element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[placeholder="Search for stocks, ETFs, cryptocurrencies, and more"]')))

# 激活输入框并输入内容
input_element.click()
input_element.send_keys('nvda stock')
input_element.send_keys(Keys.ENTER)

time.sleep(1)
driver.quit()

2. 处理页面Cookie弹窗

如果页面加载后出现Cookie同意提示,需要先关闭它,否则会遮挡搜索框:

# 在获取搜索框之前,先处理Cookie弹窗
try:
    accept_cookie_btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[aria-label="Accept all"]')))
    accept_cookie_btn.click()
except:
    # 若没有弹窗,跳过即可
    pass

3. 确保元素处于可交互状态

通过开发者工具检查定位到的元素:

  • 确认元素不是隐藏状态(display: none或visibility: hidden)
  • 若元素不在视口内,可通过JS滚动到元素位置:
driver.execute_script("arguments[0].scrollIntoView();", input_element)

关键注意事项

  • Google页面的类名是动态生成的,不要依赖Ax4B8.ZAGvjd这类易变的类名,优先使用id、name、placeholder等稳定属性
  • 显式等待是Selenium最佳实践,比time.sleep更可靠,能适配不同网络速度
  • 若仍出现问题,检查Chrome浏览器版本与ChromeDriver版本是否匹配,版本不一致也会导致交互异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 02:26:08