首页 > 解决方案 > XPath 到

哪个没有直接分配的类

问题描述

我遇到了一个问题,我需要排除一些上面有“promoted-list”类的“价格”类标签。这是一个例子

<table class="promoted-list">
<td>
<p class="price">I dont want this one</p>
</td>
</table>

<table>
<td>
<p class="price">I want this one</p>
</td>
</table>

我无法通过 XPath 访问这 1000 个使用:

//p[contains(@class, 'price') and not(contains(@class, 'promoted-list'))]

它只是不想排除这个,有人有解决方案吗?在这种情况下,输出应该是“我想要这个”

标签: htmlxpath

解决方案


给定一个格式良好的示例 XML 文档,例如

<root>
<table class="promoted-list">
<td>
<p class="price">I dont want this one</p>
</td>
</table>

<table>
<td>
<p class="price">I want this one</p>
</td>
</table>
</root>

一个 XPath 表达式来完成这将是:

//table[not(contains(@class, 'promoted-list'))]//p[contains(@class, 'price')]

用简单的英语,它的意​​思是

//table[not(contains(@class, 'promoted-list'))]//p[contains(@class, 'price')]

select all `table` elements,
       but only if they do not have a `class` attribute whose value includes "promoted-list
                                               of the remaining `table` elements, select all `p` descendant elements
                                                  but only if they have a `class` attribute whose value contains "price"

输出

<p class="price">I want this one</p>

推荐阅读