2017-06-21 8 views
0

私は、反復HTMLノードを試して、このノードから情報を取得しようとしています。HTMLユニット反復ノード

これは、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()"); 
} 

「divを」リストのサイズは4

それは、現在のノードから1つだけの結果を得ることは可能です常にありますか?

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

あなたは、インデックスによって特定の要素が必要な場合:

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

UPDATE

を多分問題は、使用されgetFirstByXPathを使用するだけで、最初に一致した要素を取得するには

答えて

1

絶対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を指定していないことがわかりました。 – Stondylus

+0

node.getByXPath( "h4/text()")戻り値null – user2264784