如何使用Jsoup解析第一个子表的行

时间:2014-10-27 20:50:22

标签: html jsoup


我的html看起来像这样:

<table>
<tbody>
    <tr>
        <table>
             <tbody>
                 <tr>
                    <td>Header 1</td>
                    <td>Value 1</td>
                </tr>
                <tr>
                    <td>Header 2 2</td>
                    <td>Value 2</td>
                </tr>
                <tr>
                    <td>Header 3</td>
                    <td>
                        Values 3 should be complete column
                        <table>
                            <tbody>
                                <tr>
                                    <th>This should go into Value 3</th>
                                    <th>This should go into Value 3 too, including its table</th>
                                </tr>
                                <tr>
                                    <td>Again Value 3</td>
                                    <td>Again into Value 3 too, including its table</td>
                                </tr>
                            </tbody>
                        </table>
                    </td>
                </tr>
                <tr>
                    <td>Header 4</td>
                    <td>Value 4</td>
                </tr>
             </tbody>
        </table>
    </tr>   
</tbody>

我试图创建一个地图,使得第1级表格的第一行成为关键,第二行成为值,无论第二个td中是什么。我面临的问题是,如果有一个完整的表位于第二个,当我真正想要它作为一个值时,它的行也会被拾取。我使用的代码是:

Document doc = Jsoup.parse(htmlText);
Elements table = doc.select("table");
Element innerTable;
if(table!=null && table.size()>1){
    innerTable = table.get(1);
}else{
    innerTable = table.get(0);
}
Elements rows = innerTable.select("tr");
for(Element row : rows){
    Elements cols = row.select("td");
    String headerFromHTML = cols.get(0).text();
    String valueFromHTML = cols.get(1).html();
    System.out.println(headerFromHTML+","+valueFromHTML);
}

预期产出:

Header 1, Value 1
Header 2, Value 2
Header 3, Value 3 should be complete td<table><tbody><tr><th>This should go into Value 3</th><th>This should go into Value 3 too, including its table</th></tr><tr><td>Again Value 3</td><td>Again into Value 3 too, including its table</td></tr></tbody></table>
Header 4, Value 4

但是实际输出不会产生这个。该行实际上也包含内部tr,我没有得到理想的结果。事实上,由于th,它也会抛出一个异常(可以处理,但这个tr实际上应该有价值) 我该如何修改我的代码。请帮忙。

1 个答案:

答案 0 :(得分:0)

一个大多数标签都在错误的地方。 两个你定义了太多次表。 对于三个组织需要改进。 这里四个是它应该基本上看起来

<table style="width:100%">
 <tr>
  <td></td>
  <td></td>     
  <td></td>
 </tr>
 <tr>
  <td></td>
  <td></td>     
  <td></td>
 </tr>
 <tr>
  <td></td>
  <td></td>     
  <td></td>
 </tr>
</table>

请记住,HTML会按顺序显示元素,除非被其他语言更改