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

如何使用XPath按属性名选择元素并排除相同子元素?

如何使用XPath按属性名选择元素并排除包含同类子元素的节点?

问题背景

给定以下HTML结构:

<div c-store="test">
    <div c-text>Product Name</div>
    
    <div c-store="test">
        <div c-text>Product Name</div>

        <div c-store="test">
            <div c-text>Product Name</div>
        </div>
    </div>
</div>

需要筛选出所有带有c-store="test"属性的<div>元素,但要求这些元素内部不能包含任何同样带有c-store="test"属性的子元素,最终期望得到的结果是:

<div c-store="test">
    <div c-text>Product Name</div>
</div>

解决方案

使用以下XPath表达式即可实现需求:

//div[@c-store="test" and not(.//div[@c-store="test"])]

表达式解释

  • //div[@c-store="test"]:匹配文档中所有带有c-store="test"属性的<div>元素
  • and not(.//div[@c-store="test"]):添加筛选条件,排除那些自身后代节点中存在同样带有c-store="test"属性的<div>的节点
  • 组合后只会选中最底层、无同类嵌套的c-store元素,完全符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:05:05