【问题标题】:Extract table row data using JSoup returns nothing使用 JSoup 提取表行数据不返回任何内容
【发布时间】:2016-04-25 20:43:50
【问题描述】:

我正在尝试使用 JSoup 库提取表格行数据。但它没有给我任何输出结果。

到目前为止,这是我的代码:

String html = "<tbody>"
                + "<tr>"
                + "<td><strong>Fit</strong></td>"
                + "<td>Regular</td>"
                + "</tr>"
                + "<tr>"
                + "<td><strong>Color</strong></td>"
                + "<td>Multi</td>"
                + "</tr>"
                + "<tr>"
                + "<td><strong>Style</strong></td>"
                + "<td>Checked</td>"
                + "</tr>"
                + "<tr>"
                + "<td><strong>Fabric</strong></td>"
                + "<td>Cotton</td>"
                + "</tr>"
                + "<tr>"
                + "<td><strong>Model Stats</strong></td>"
                + "<td> This model has height 5'9\",Bust 32\",Waist 28\",Hip 36\"and is Wearing Size 10.</td>"
                + "</tr>"
                + "</tbody>";

        Document doc = Jsoup.parse(html);


        for (Element table : doc.select("tbody")) {
            for (Element row : table.select("tr")) {
                Elements tds = row.select("td");
                for (Element td : tds) {
                    System.out.println(td.text());
                }
            }
        }

如果有人能向我推荐一种如下所示的输出方法,我们将不胜感激:

<strong>Fit</strong>
Regular
<strong>Color</strong>
Multi
<strong>Style</strong>
Checked
<strong>Fabric</strong>
Cotton ... etc..

谢谢。

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    问题在于您的 html。您应该在 html 变量的 startend 处添加 &lt;table&gt;&lt;/table&gt;,否则 Jsoup 将无法正确解析您的 html,导致您的 &lt;tbody&gt; 转换为 &lt;body&gt;,这就是您无法在查询中选择它的原因。

    此外,要生成所需的输出,请使用 td.html() 而不是 td.text()

    【讨论】:

    • 非常感谢。它适用于您的更正。 :)
    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 2017-03-21
    • 2022-07-31
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多