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

如何使用Selenium Python按指定文本提取HTML关联元素的内容

Selenium Python批量提取指定单元格内容方案

实现思路

根据你给出的HTML结构,符合要求的条目按固定顺序排列:error-snip-cell单元格 → 紧邻的error-id-cell单元格 → 紧邻的error-message-cell单元格,按这个顺序匹配提取即可。

完整实现代码

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

# 初始化浏览器(这里以Chrome为例,可替换为其他浏览器驱动)
driver = webdriver.Chrome()
# 打开目标页面
driver.get("替换为你的目标页面URL")

# 设置显式等待,最长等待10秒,避免元素未加载导致匹配失败
wait = WebDriverWait(driver, 10)

# 匹配所有符合文本要求的snip单元格
# 使用normalize-space处理文本前后的空格、换行符,避免匹配失败
target_snip_xpath = '''
//td[
    @class="error-snip-cell xdata-label-text" 
    and (normalize-space(text())="2 - H Syntax" or normalize-space(text())="4 - Situational")
]
'''
target_snips = wait.until(EC.presence_of_all_elements_located((By.XPATH, target_snip_xpath)))

# 存储提取结果
result = []
for snip in target_snips:
    # 提取对应id:snip单元格的下1个兄弟td元素
    error_id = snip.find_element(
        By.XPATH, './following-sibling::td[1][@class="error-id-cell xdata-label-text"]'
    ).text.strip()
    # 提取对应错误信息:snip单元格的下2个兄弟td元素
    error_msg = snip.find_element(
        By.XPATH, './following-sibling::td[2][@class="error-message-cell xdata-value-text"]'
    ).text.strip()
    # 存入结果
    result.append({
        "error_type": snip.text.strip(),
        "error_id": error_id,
        "error_message": error_msg
    })

# 打印结果验证
for item in result:
    print(item)

# 操作完成关闭浏览器
driver.quit()

优化说明

如果页面的td元素class属性后续可能新增其他类名、或者有多余空格,可把xpath中的@class="xxx"替换为contains(@class, "xxx")做模糊匹配,比如:

//td[
    contains(@class,"error-snip-cell") 
    and contains(@class,"xdata-label-text") 
    and (normalize-space(text())="2 - H Syntax" or normalize-space(text())="4 - Situational")
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:27:05