XPath:嵌套方括号是什么意思?

bla*_*alb 3 html xml xpath web-scraping

我正在学习用于网页抓取的 XPath,并偶然发现了这两个 XPath 示例:

//div[@class="head"][@id="top"]
Run Code Online (Sandbox Code Playgroud)

//div[@class='canvas- graph']//a[@href='/accounting.html'][i[@class='icon-usd']]/following-sibling::h4
Run Code Online (Sandbox Code Playgroud)

我想知道这是什么div[@class="head"][@id="top"]意思。这是否意味着该@id=top属性属于该div元素?是一样的//div[@class="head" and @id="top"]吗?
当方括号嵌套在另一个示例中时,这意味着什么?匹配第二个 xpath 表达式的 HTML DOM 会是什么样子?

kjh*_*hes 5

方括号分隔谓词,谓词过滤项††

您预计可以通过两种方式组合谓词:

  1. 连续:是的,这相当于逻辑上ing 谓词。所以,正确的,//div[@class="head"][@id="top"]等价于//div[@class="head" and @id="top"].

  2. 递归:是的,XPath 允许谓词内的谓词(嵌套,如您所见)。

    所以,a[@href='/accounting.html'][i[@class='icon-usd']]过滤器的那些a与元素@href的属性值等于'/accounting.html' 一个子i带元件@class属性值等于'icon-usd'

这些组合机制共同提供了一种从更基本的条件构建谓词的强大方法。


谓词引用:XPath 1.0XPath 3.1
†† XPath 1.0 中的节点集; XPath 2.0+ 中的序列