2013-05-09 167 views
0

我有以下的HTML文檔的XPath搜索多個嵌套元素

<div class="books"> 
    <div class="book"> 
    <div> 
     there are many deep nested elements here, somewhere there will be one span with some text e.g. 'mybooktext' within these 
     <div> 
     <div> 
      <div> 
      <span>mybooktext</span> 
      </div> 
     </div> 
    </div> 
    </div> 
<div> 
there are also many nested elements here, somewhere there will be a link with a class called 'mylinkclass' within these. (this is the element i want to find) 
<div> 
    <div> 
    <a class="mylinkclass">Bla</a> 
    </div> 
</div> 
</div> 
</div> 
<div class="book"> 
<div> 
there are many deep nested elements here, somewhere there will be one span with some  text e.g. 'mybooktext' within these 
    <div> 
    <span>mybooktext</span> 
    </div> 
<div> 
</div> 
<div> 
there are also many nested elements here, somewhere there will be a link with a class called 'mylinkclass' within these. (this is the element i want to find) 
<div> 
    <a class="mylinkclass">Bla</a> 
</div> 
</div> 
</div> 
<div class="book"> 
same as above 
</div> 
</div> 

我想找到的鏈接元素(鏈路級稱爲「mylinkclass」),這將是基於文本的書元素中在同一書籍元素內的跨度。

因此,這將是這樣的:

  1. - 查找跨度文本 'mybooktext'

  2. -Navigate了書的div

  3. 與類中的 'mylinkclass' - 查找鏈接book div

這應該使用一個xpath s來完成tatement

+0

您能否重新考慮您的示例?它會匹配你的xpath請求。 「mybooktext」是跨度中的唯一文本還是文本的一部分? – 2013-05-09 19:37:03

+0

'mybooktext'將是唯一的文本。 – user1786107 2013-05-09 19:43:57

回答

4

在我的幾個,這是在您正在尋找:

" //span[contains(text(),'mybooktext')] 
      /ancestor::div[@class='book'] 
      //a[@class='mylinkclass']" 

//span[contains(text(),'mybooktext')]查找包含SAN 「mybooktext」
/ancestor::div[@class='book']向上導航書格(在任何深處)與類
//a[@class='mylinkclass'] Find鏈接「 mylinkclass'內的書div(在任何深度)

更新: 更改第一個條件爲
//span[(text() ='mybooktext']如果mybooktext是範圍中唯一的文本

+0

非常感謝。我現在不在電腦,但明天會測試,並將其標記爲答案。再次感謝 – user1786107 2013-05-09 19:59:52

+0

您在此期間嘗試過嗎? – 2013-05-10 17:15:57