【问题标题】:xpath find node that does not contain childxpath 查找不包含子节点的节点
【发布时间】:2023-12-26 03:48:01
【问题描述】:

我正在尝试创建一些 xpath,它将找到所有不包含 img 标签的 a 标签,以便诸如

<a href="http://aol.com">link</a>

匹配,但是

<a href="http://yahoo.com"><img src="http://yahoo.com/logo.png"></a>

没有。

当然,我可以通过两部分搜索来做到这一点,但我确信一定有某种方法可以用 xpath 做到这一点。

【问题讨论】:

    标签: xpath html-parsing xml-parsing


    【解决方案1】:
    //a[not(img)]
    

    如果可以的话,尽量避免使用//。另请注意,这只会排除直接包含imgs的as。

    【讨论】:

    • XPath 表达式,用于 “任何不具有 img 后代元素的 a 元素”//a[not(.//img)]
    • 我需要第一个没有链接的 td //table/tr/td[1][not(a) and not(b)]。 html 使用 td 作为表头,表头被包裹在 &lt;b&gt; 中,所以我也不得不跳过这些。