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

基于Selenium通过CSS选择器和ID抓取SVG悬停数据

解决SVG悬停气泡数据抓取问题

问题原因分析

  1. XPath语法错误:原代码中label_xpath的@id = 'ballons')多了一个右括号,导致XPath完全失效。
  2. 悬停动作未执行:action.move_to_element(polygon)仅定义了动作,未调用perform()执行,鼠标实际未移动到目标path元素上。
  3. 未等待动态元素加载:悬停触发的气泡是动态生成的DOM元素,需等待元素渲染完成后再进行定位。
  4. 展开按钮逻辑错误:原代码用find_element仅定位第一个按钮,循环点击10次实际是重复点击同一按钮,未真正展开所有行。

修正后的代码

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

# 目标网页URL
target_url = "https://transparency.entsoe.eu/congestion-management/r2/redispatching-internal/show?name=&defaultValue=false&viewType=GRAPH&areaType=CTA&atch=false&dateTime.dateTime=01.01.2022%2000:00%7CUTC%7CDAY&dateTime.endDateTime=02.01.2023%2000:00%7CUTC%7CDAY&area.values=CTY%7C10Y1001A1001A83F!CTA%7C10YDE-VE-------2&dv-datatable_length=10"

driver = webdriver.Chrome()
action = ActionChains(driver)
wait = WebDriverWait(driver, 10)

driver.get(target_url)

# 关闭弹窗与Cookie提示
wait.until(EC.element_to_be_clickable((By.ID, "close-button"))).click()
wait.until(EC.element_to_be_clickable((By.ID, "cookieconsent-button"))).click()

# 展开所有表格行的[+]按钮
expand_button_xpath = "//table[@class='data-view-table redispatching dataTable']//tr//td[@class='button-column']//a[@class='openIcon pre-table-button operation-detail-expand small-button ui-button-light ui-button ui-widget ui-corner-all ui-button-text-only']"
expand_buttons = wait.until(EC.presence_of_all_elements_located((By.XPATH, expand_button_xpath)))
for button in expand_buttons:
    if button.is_displayed() and button.is_enabled():
        driver.execute_script("arguments[0].click();", button)

# 获取所有SVG路径元素
path_elements = wait.until(EC.presence_of_all_elements_located((By.TAG_NAME, 'path')))

# 修正后的XPath:定位Capacity Impact的数值tspan元素
capacity_impact_xpath = "//*[name()='svg']//*[name()='g' and @id='ballons']//*[name()='tspan' and contains(text(), 'Capacity Impact')]/following-sibling::*[name()='tspan']"

for path in path_elements:
    try:
        # 执行鼠标悬停动作
        action.move_to_element(path).perform()
        # 等待气泡加载并获取数值
        impact_value = wait.until(EC.presence_of_element_located((By.XPATH, capacity_impact_xpath))).text
        print(f"Capacity Impact: {impact_value}")
    except Exception:
        # 部分路径无悬停气泡,跳过
        continue

driver.quit()

关键优化说明

  • 修复XPath语法:移除多余的右括号,同时优化XPath直接定位数值所在的tspan(跟随在"Capacity Impact"文本后的兄弟元素),提升定位精准度。
  • 执行悬停动作:添加perform()方法让鼠标真正移动到目标元素上,触发气泡显示。
  • 动态元素等待:使用WebDriverWait等待气泡元素出现,避免因DOM未更新导致的空列表问题。
  • 正确展开按钮:遍历所有找到的展开按钮,用execute_script点击避免元素遮挡或交互限制问题。
  • 异常处理:捕获部分路径无悬停气泡的异常,避免程序中断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:00:37