2016-03-21 31 views
1

テーブル内の特定のタイトルの値を抽出する。Jsoupが属性を含む場合に値を取得する

<tr> 
    <th colspan="8"> 
    <a href="/wiki/Hit_points" title="Hit points" class="mw-redirect">Hit points</a> 
    </th> 
    <td colspan="12"> 240</td> 
    </tr> 
<tr> 
<th colspan="8"> <a href="/wiki/Aggressive" title="Aggressive" class="mw-redirect">Aggressive</a> 
</th><td colspan="12"> Yes 
</td></tr> 

たとえば、値を取得できます。

タイトルが等しい場合、この場合の240

を返し "ヒットポイント"。

package test; 

import org.jsoup.Connection.Response; 
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Attribute; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 
import org.jsoup.select.Elements; 

public class topkek { 

    public static void main(String[] args) { 
     try { 
     Response res = Jsoup.connect("http://2007.runescape.wikia.com/wiki/King_black_dragon").execute(); 
      String html = res.body(); 
      Document doc2 = Jsoup.parseBodyFragment(html); 
      Element body = doc2.body(); 
      Elements tables = body.getElementsByTag("table"); 
      for (Element table : tables) { 


       if (table.className().contains("infobox")==true) { 
        System.out.println(table.getElementsByAttribute("title").text()); 
        break; 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

答えて

1

手動で文書を通過する必要はありません、あなたは、単にこのためセレクタを使用することができます。

response 
    .parse() 
    .select("th:has(a[title=\"Hit points\"]) ~ td") 
    .text() 

これはタイトルのネストされたaを持ち、兄弟を持っているth要素を選択tdコンテンツを読むことができる要素text()

構文の詳細についてはhere、オンラインサンドボックスの場合はhereを参照してください。

編集

document 
    .select("th:has(a[title])") 
    .forEach(e -> { 
     System.out.println(e.text()); 
     System.out.println(((Element) e.nextSibling()).text()); 
    }); 
:あなたは複数の要素を一覧表示したい場合は、このようなものを使用することができます
関連する問題