2017-06-21 78 views
0

我嘗試迭代html節點並從此節點獲取信息。HTMLunit迭代節點

這是HTML例如:

<div class="less1"> 
    <h4>Test name 1</h4> 
    <div> 
    <div id="email">[email protected]</div> 
    <div id="email">[email protected]</div> 
    <div id="email">[email protected]</div> 
    </div> 
</div> 
<div class="less1"> 
    <h4>Test name 2</h4> 
    <div> 
    <div id="email">[email protected]</div> 
    <div id="email">[email protected]</div> 
    <div id="email">[email protected]</div> 
    </div> 
</div> 
<div class="less1"> 
    <h4>Test name 3</h4> 
    <div> 
    <div id="email">[email protected]</div> 
    </div> 
</div> 
<div class="less1"> 
    <h4>Test name 4</h4> 
</div> 

這是我的代碼示例。

final List<HtmlListItem> nodes = htmlPage.getByXPath("//*[@class=\"less1\"]"); 

for (HtmlListItem node: nodes) { 
    final List<?> divs = node.getByXPath("//h4/text()"); 
} 

「申報單」列出的大小總是4

是否有可能從當前節點只得到1的結果?

回答

1

爲了只得到第一個匹配的元素中使用getFirstByXPath

final List<?> divs = node.getFirstByXPath("//h4/text()"); 

如果通過索引需要一個特定的元素:

final Object div = node.getByXPath("//h4/text()").get(index); 

UPDATE

也許問題是使用的絕對xpath。 嘗試使用每個節點上的相對路徑:

String text = node.getByXPath("h4/text()"); 
List<String> emails = node.getByXPath("div/div"); 

否則,你可以探索子節點

for (HtmlListItem node: nodes) { 
    NodeList children = node.getChildNodes(); 
    for (int i = 0; i < children.getLength(); i++) { 
     Node child = children.item(i); 
     /** extract data from child **/ 
    }  
} 
+0

是的,你可以做到這一點從每個節點中提取數據,但我希望得到幾乎其他信息在這個div裏面。我更新了html示例。我想從

標記中獲得1個節點文本,並從ID爲「email」的元素中獲取所有電子郵件 – user2264784

+1

我只是看到您沒有指定相對xPath。嘗試使用node.getByXPath(「h4/text()」) – Stondylus

+0

node.getByXPath(「h4/text()」)返回null – user2264784