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

如何抓取鼠标悬停元素文本?解决Selenium迭代报错问题

问题解决:抓取CPU价格历史Tooltip信息的Selenium错误修复及替代方案

一、错误原因

你代码里的EC.presence_of_element_located()返回的是单个WebElement对象,不是可迭代的列表,所以用for el in element会触发'WebElement' object is not iterable错误。另外,定位Tooltip的By.SELECTOR是错误写法,应该用By.CSS_SELECTOR,且原选择器也不准确。

二、修改后的Selenium模拟悬停代码

因为Canvas是画布元素,内部数据点没有独立DOM节点,所以需要通过坐标偏移来模拟鼠标遍历:

from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")
webdriver_service = Service()
driver = webdriver.Chrome(options=options, service=webdriver_service)

driver.get('https://www.cpubenchmark.net/cpu.php?cpu=Intel+Core+i9-11900K+%40+3.50GHz&id=3904')

# 等待价格历史图表加载
chart_canvas = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, "//*[@id='placeholder']/div/canvas[2]"))
)

# 获取画布的位置和尺寸
canvas_loc = chart_canvas.location
canvas_size = chart_canvas.size

# 按固定间隔遍历画布水平方向,模拟鼠标悬停
step = 20  # 间隔越小,遍历越精细
for x in range(0, canvas_size['width'], step):
    # 移动鼠标到画布内对应坐标
    ActionChains(driver)\
        .move_to_element_with_offset(chart_canvas, x, canvas_size['height']//2)\
        .perform()
    
    try:
        # 等待Tooltip出现并获取内容
        tooltip = WebDriverWait(driver, 2).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, ".canvasjs-chart-tooltip"))
        )
        print(tooltip.text)
    except:
        # 跳过无Tooltip的区域
        continue

driver.quit()

三、更高效的方案:直接提取页面原始数据

Canvas图表的数据源通常存在页面的JS变量里,不需要模拟悬停,直接提取更稳定快速:

import json
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument("start-maximized")
webdriver_service = Service()
driver = webdriver.Chrome(options=options, service=webdriver_service)

driver.get('https://www.cpubenchmark.net/cpu.php?cpu=Intel+Core+i9-11900K+%40+3.50GHz&id=3904')

# 执行JS获取价格历史数据
price_data = driver.execute_script("return window.chartData[1].dataPoints;")

# 遍历打印日期和价格
for item in price_data:
    print(f"日期: {item['label']}, 价格: ${item['y']}")

driver.quit()

这个方法的好处:

  • 无需模拟鼠标,执行速度快
  • 直接拿到完整原始数据,不会遗漏
  • 避免Tooltip定位不稳定的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 12:06:16