2009-10-08 72 views
21

在使用Selenium定位網頁中的元素時,我使用了很多XPath,並且已經從最近使用node1 // node2轉向使用node1/descendant :: node2。這兩種方法有什麼區別?比另一個更有效率嗎?xpath中的// node和/ descendant :: node有什麼區別?

示例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> 

所以它會是:

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

或:

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

回答

24

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

//只是一個d的縮寫escendant ::軸

編輯

引述:

//對短的/後裔或自身::節點()/ child :: para的

也就是說,它指代作爲上下文節點的子節點或從上下文節點下降的任何節點的所有段。據我可以說,翻譯成上下文節點的任何後代段。

+1

採取我應該問之前已經走遍了TR。對於其他人http://www.w3.org/TR/xpath#path-abbrev是相關部分。這似乎表明,//對於後代或自己來說不完全相同。另外,我不使用//的原因是// node [1]不同於/ descendant :: node [1] – 2009-10-08 13:36:09

+1

我已經在上面的那點展開了。 //不是後代或自我,它是後代或自己/孩子......這對我來說看起來非常像後裔。 – 2009-10-08 13:38:26

+0

同意。注意到。 :) – 2009-10-08 13:40:59

2

除了簡潔,我沒有意識到任何區別。

8

上下文組有所不同。 //para[1]/descendant-or-self::node()/child::para[1]的簡稱,它返回每個父節點的第一個子節點。 /descendant::para[1]僅返回整個子樹中的第一個段落。

+0

另外(// para)[1]也可以工作,但不會在Selenium 1中使用,因此您必須使用/ descendant :: para [1]。任何人都知道// node [1]和/ descendant :: node [1]之間的上下文組是如何應用的? – 2013-04-19 04:06:31

4

在你的情況

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

和:

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

返回相同的結果。

但實際上,就像之前已經說過的那樣,id('books')//td[@class='title']表示id('books')/descendant-or-self::node()/td[@class='title']id('books')/descendant::td[@class='title']的概念不同。

請參見下面的註釋:

注意:地址路徑//第[1],並不意味着一樣的位置路徑/後裔::第[1]。後者選擇第一個後代para元素;前者選擇所有父系的第一個para para孩子的後代para元素。

本說明是從http://www.w3.org/TR/xpath#path-abbrev

相關問題