xpath中// node和/ descendant :: node之间有什么区别?

Dav*_*unt 32 xpath

我在使用Selenium在网页中定位元素时使用了大量的XPath,并且最近已经从使用node1 // node2转向使用node1/descendant :: node2.这两种方法有什么区别?一个比另一个更有效吗?

用于演示的示例XML代码段:

<div id="books">
  <table>
    <tr><td class="title">Lord of the Rings</td><td class="author">JRR Tolkein</td></tr>
    <tr><td class="title">The Hitch-Hikers Guide to the Galaxy</td><td class="author">Douglas Adams</td></tr>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)

所以它是:

id('books')//td[@class='title']

要么:

id('books')/descendant::td[@class='title']

Jon*_*and 35

http://www.w3.org/TR/xpath#path-abbrev

//只是descendant :: axis的缩写

编辑

报价:

// para是/ descendant-or-self :: node()/ child :: para的缩写

也就是说,它指的是所有的para,它们是上下文节点的子节点或者来自上下文节点的任何节点.据我所知,它转换为上下文节点的任何后代段.


小智 11

上下文组有所不同.//para[1]是的缩写 /descendant-or-self::node()/child::para[1],它返回作为其父级的第一个子节点的每个段. /descendant::para[1]仅返回整个子树中的第一个段.


小智 5

在你的情况下

 id('books')//td[@class='title']
Run Code Online (Sandbox Code Playgroud)

和:

 id('books')/descendant::td[@class='title']
Run Code Online (Sandbox Code Playgroud)

返回相同的结果。

但实际上,就像之前已经说过的那样,id('books')//td[@class='title']意味着id('books')/descendant-or-self::node()/td[@class='title']id('books')/descendant::td[@class='title']概念不同。

请参阅以下说明:

注意:位置路径 //para[1] 与位置路径 /descendant::para[1] 的含义不同。后者选择第一个后代 para 元素;前者选择作为其父母的第一个 para 孩子的所有后代 para 元素。

此注释取自http://www.w3.org/TR/xpath#path-abbrev