如何用jsoup动态抓取每个表tr的第一个字段?

时间:2013-02-19 13:22:18

标签: android jsoup

我想将此表的名称和日程表分开存储在数据库中,验证是否已在字段中包含某些数据。

<table class="linha-horas">
 <tbody>
  <tr>
   <th><h5>Profipo p/ Itaum</h5></th>
   <th><h5>Itaum p/ Ulysses G</h5></th>
   <th><h5>Ulysses G. p/ Itaum</h5></th>
   <th><h5>Itaum p/ Profipo</h5></th>
  </tr>
  <tr>
   <td>12:49</td>
   <td>05:46</td>
   <td>05:55</td>
   <td>06:08</td>
  </tr>
  <tr>
   <td>18:05</td>
   <td>13:12</td>
   <td>06:31</td>
   <td>06:44</td>
  </tr>
  <tr>
   <td class="empty"></td>
   <td>18:29</td>
   <td>11:01</td>
   <td>11:14</td>
  </tr>
 </tbody>
</table>

我想要的结果示例:

Profipo p/ Itaum
12:49
18:05

Itaum p/ Ulysses G
05:46
13:12
18:29

并且动态地如果表包含更多计划......

韩国社交协会

1 个答案:

答案 0 :(得分:0)

提示是在选择中使用:eq(),请在下面找到代码:

public final static String stack = "<table class=\"linha-horas\">"
 +"<tbody><tr><th><h5>Profipo p/ Itaum</h5></th><th><h5>Itaum p/ Ulysses G</h5>"
 + "</th><th><h5>Ulysses G. p/ Itaum</h5></th><th><h5>Itaum p/ Profipo</h5></th></tr>"
 + "<tr><td>12:49</td><td>05:46</td><td>05:55</td><td>06:08</td></tr>"
 + "<tr><td>18:05</td><td>13:12</td><td>06:31</td><td>06:44</td></tr>"
 + "<tr><td class=\"empty\"></td><td>18:29</td><td>11:01</td><td>11:14</td></tr>"
 + "</tbody></table>";

public static void main(String[] args){
    System.out.println("the html content to parse is: "+stack);
    Document doc = Jsoup.parse(stack);
    Elements ths = doc.select("th");
    for(int i = 0; i < ths.size(); i++)
    {
        System.out.println(ths.get(i).text());//header
        Elements tds = doc.select("tr td:eq("+i+")");//rows
        for(Element td : tds)
        {
            System.out.println(td.text());
        }
    }
}

以下是输出:

the html content to parse is: <table class="linha-horas"><tbody><tr><th><h5>Profipo p/ Itaum</h5></th><th><h5>Itaum p/ Ulysses G</h5></th><th><h5>Ulysses G. p/ Itaum</h5></th><th><h5>Itaum p/ Profipo</h5></th></tr><tr><td>12:49</td><td>05:46</td><td>05:55</td><td>06:08</td></tr><tr><td>18:05</td><td>13:12</td><td>06:31</td><td>06:44</td></tr><tr><td class="empty"></td><td>18:29</td><td>11:01</td><td>11:14</td></tr></tbody></table>
Profipo p/ Itaum
12:49
18:05

Itaum p/ Ulysses G
05:46
13:12
18:29
Ulysses G. p/ Itaum
05:55
06:31
11:01
Itaum p/ Profipo
06:08
06:44
11:14