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

Selenium如何抓取鼠标悬停元素时显示的赔率文本?

解决鼠标悬停获取赔率值的问题

问题背景

在某意甲赛事页面中,鼠标悬停指定元素时会弹出包含历史赔率的行(如示例HTML里的2.26),但原有代码无法成功提取该值。对应的核心HTML结构如下:

<div class="history-row history normal-odds">
  <span class="time">Feb 26, 20:47</span>
  <b class="odd-value">2.26</b>
  <span class="arrow-up arrH">▲</span>
  (<span class="sign sgnp">+0.01</span>)
</div>

原代码问题分析

原有代码存在几处关键问题:

  • 悬停元素用了硬编码的tr[19]定位,页面结构变动就会失效
  • 悬停后直接取整个history-row的文本,没法精准拿到2.26这个单独值
  • 等待时间太短(仅2秒),容易出现元素未加载完成就操作的情况

修正后的代码方案

单个元素提取

如果只需提取单个悬停元素的赔率值:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 初始化浏览器(根据你的实际浏览器调整,比如Chrome/Firefox)
wbe = webdriver.Chrome()
wbe.get('https://www.oddsmath.com/football/italy/serie-a-1315/2023-02-26/ac-milan-vs-atalanta-4052172/#DC')

# 等待目标悬停元素加载完成(可根据实际情况调整定位器)
hover_el = WebDriverWait(wbe, 10).until(
    EC.visibility_of_element_located((By.XPATH, '//*[@id="table-odds-cat-0"]/tbody/tr[19]/td[3]/div[2]'))
)

# 执行鼠标悬停操作
ActionChains(wbe).move_to_element(hover_el).perform()

# 等待历史赔率行出现,精准提取赔率值
odd_value = WebDriverWait(wbe, 10).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, '.history-row .odd-value'))
).text

print(f"提取到的赔率值:{odd_value}")

# 关闭浏览器
wbe.quit()

批量元素提取

如果需要处理多个悬停元素:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wbe = webdriver.Chrome()
wbe.get('https://www.oddsmath.com/football/italy/serie-a-1315/2023-02-26/ac-milan-vs-atalanta-4052172/#DC')

# 等待所有目标悬停元素加载
hover_elements = WebDriverWait(wbe, 10).until(
    EC.visibility_of_all_elements_located((By.XPATH, '//*[@id="table-odds-cat-0"]/tbody/tr[19]/td[3]/div[2]'))
)

for el in hover_elements:
    # 悬停当前元素
    ActionChains(wbe).move_to_element(el).perform()
    # 等待对应赔率弹窗加载,提取值
    odd_val = WebDriverWait(wbe, 5).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, '.history-row .odd-value'))
    ).text
    print(f"提取到的赔率值:{odd_val}")

wbe.quit()

关键改进说明

  • 精准定位目标值:用CSS选择器.history-row .odd-value直接定位存储赔率的<b>标签,避免提取多余的时间、箭头等文本
  • 优化等待逻辑:把超时时间调整到10秒,用WebDriverWait替代固定sleep,确保元素完全加载后再操作,稳定性更高
  • 灵活适配场景:分单个/批量两种场景,批量处理时给每个悬停操作单独设置短等待,避免元素加载冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 02:28:18