【问题标题】:How to use the exclude filter syntax in Xpath如何在 Xpath 中使用排除过滤器语法
【发布时间】:2021-09-24 02:55:53
【问题描述】:

我正在尝试使用 Xpath 解析我公司的 HTML,以下是我的目标网站的示例 html 结构:

<div class='my_target' id='A'>
    This is a sample website HTML!
    <span>APPLE</span>

    <span>BANANA</span>

    <span>ORANGE</span>

    <span>IGNORE_1</span>

    <span>IGNORE_2</span>

</div>


<div class='not_my_target' id='B'>
    This is a sample website HTML!
    <span>APPLE</span>

    <span>BANANA</span>

    <span>ORANGE</span>

    <span>IGNORE_1</span>

    <span>IGNORE_2</span>
</div>

这是我想要得到的元素:

<div class='my_target' id='A'>
This is a sample website HTML!
    <span>APPLE</span>

    <span>BANANA</span>

    <span>ORANGE</span>
</div>

我试过这样的代码:

//div[@id='A' and (not(self::span and contains(text(), "IGNORE_1")) or not(self::span and contains(text(), "IGNORE_2"))]

但是没用Q_Q

我写错语法了吗?有谁可以帮忙?

谢谢 

【问题讨论】:

  • 您想同时选择div 或spans 中的span 元素以及div 吗?
  • @Prophet 我想选择整个
    ,并排除两个“IGNORE_x” 元素。
  • 使用 XPath,您可以获取元素及其 all 的子元素。否则你需要使用 XSLT

标签: html web xpath xml-parsing


【解决方案1】:

试试这个:

//div[@id='A']/span[not(contains(text(),'IGNORE_1')) and not(contains(text(),'IGNORE_2'))]

这将搜索A 的ID 值,然后检查span 是否不包含IGNORE_1 和IGNORE_2。

您的案例有问题:

您正在搜索 ID 并设置不应包含 span、IGNORE_1 和 IGNORE_2 的条件。这就是为什么你无法得到想要的结果。

//div[@id='A' and (not(self::span and contains(text(), "IGNORE_1")) or not(self::span and contains(text(), "IGNORE_2"))]

【讨论】:

  • 您好,感谢您的回答。我试过你的代码,但我发现 xpath 只能正确捕获三个 元素,句子'This is a sample website HTML!'不会出现。有什么办法可以包含这句话吗? THX
猜你喜欢
相关资源
最近更新 更多
热门标签