2017-02-02 40 views
2

當頁面調整大小時,我有一個鏈接隱藏了元素,所以即時通過前一個元素嘗試獲取該元素。使用Xpath獲取前面的兄弟姐妹

<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"> 
     <i class="icon icon-doc-new"></i> 
     <span class="hidden-sm dropdown-label">Create</span> 
     <span class="caret hidden-sm"></span> 
    </a> 

獲得 「正常」 的元素我使用XPath:

.//*[@id='main-menu']/li/a/span[contains(text(), 'Create')] 

的話,我想獲得元素<i class="icon icon-doc-new"></i> 像這樣

.//*[@id='main-menu']/li/a/span[contains(text(), 'Create')]/precending-sibling::i[0] //(also tried different indexes] 

試過一對夫婦其他方法,但沒有去。

任何提示?

回答

1

試試用下面XPath

.//*[@id='main-menu']/li/a[span[text()="Create"]]/i 
+0

這工作馬上。你介意多解釋一下爲什麼? – Dymond

+1

其實,我剛剛注意到你的'XPath'表達式中有一個輸入錯誤:'前同胞'應該是'前同胞'。所以你的'XPath'也應該是正確的。我的意思是用'[1]'索引,而不是'[0]' – Andersson

1

所以,如果我是正確的,並且不在兄弟姐妹之前,你實際上需要父元素。

嘗試用.//*[@id='main-menu']/li/a/span[contains(text(), 'Create')]/parent::a

如果你想前置兄弟然後用.//*[@id='main-menu']/li/a/span[contains(text(), 'Create')]/precending-sibling::i

+0

謝謝!這工作。當然現在當我看到它的父::一個。 謝謝 – Dymond

1

嘗試以下任一提到xpath

//span[@class='caret hidden-sm']/..//preceding-sibling::span[text()= 'Create'] 

xpath的說明: -使用class屬性的<span>標記,並使用preceding-sibling keyword與另一個<span>標記一起向前移動text方法。

OR

//span[@class='caret hidden-sm']/..//preceding-sibling::span[@class='hidden-sm dropdown-label'] 

的XPath的說明: -使用class<span>標籤的屬性,並使用preceding-sibling keywordclass屬性沿另一<span>標籤前進。