如何在 Xpath 中使用排除过滤器语法

How to use the exclude filter syntax in Xpath

我正在尝试使用 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[@id='A']/span[not(contains(text(),'IGNORE_1')) and not(contains(text(),'IGNORE_2'))]

这将搜索 A 的 ID 值,然后检查不包含 IGNORE_1IGNORE_2 的跨度。

您的案例有问题:

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

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