如何使用 JSoup 打印 HTML table 的内容?

How can I print the contents of this HTML table using JSoup?

我首先要说明,就此而言,使用 HTML 和 JSoup 对我来说非常陌生,所以如果这是一个愚蠢的问题,我深表歉意。

我试图用我的代码实现的是将此 link https://www.stormshield.one/pve/stats/daviddean/sch 上的 table 的内容打印到我的控制台中,每个条目的格式如下:

墙上发射器 50 等级等级等级等级等级等级 15% 冲击击退 42% 装填速度 15% 冲击击退 42% 装填速度 15% 冲击击退 42% 耐久度

我的主要问题几乎是为 table 和行提供正确的名称,一旦我可以做到这一点,格式对我来说就不是真正的问题了。

这是我尝试使用但无济于事的代码:

    public static void main(String[] args) throws IOException {

    Document doc = Jsoup.connect("https://www.stormshield.one/pve/stats/daviddean/sch").get();

    for (Element table : doc.select("table schematics")) {
        for (Element row : table.select("tr")) {
            Elements tds = row.select("td");
                System.out.println(tds.get(0).text() + ":" + tds.get(1).text());
        }
    }

}

您需要找到您的 table 元素,它是 head 和 rows。

注意,它并不总是 first() 元素,我添加它作为示例。

这是您需要做的:

Document doc = null;
try {
    doc = Jsoup.connect("https://www.stormshield.one/pve/stats/daviddean/sch").get();
} catch (IOException e) {
    e.printStackTrace();
}

Element table = doc.body().getElementsByTag("table").first();

Element thead = table.getElementsByTag("thead").first();

StringBuilder headBuilder = new StringBuilder();

for (Element th : thead.getElementsByTag("th")) {
    headBuilder.append(th.text());
    headBuilder.append(" ");
}

System.out.println(headBuilder.toString());

Element tbody = table.getElementsByTag("tbody").first();

for (Element tr : tbody.getElementsByTag("tr")) {
    StringBuilder rowBuilder = new StringBuilder();

    for (Element td : tr.getElementsByTag("td")) {
        rowBuilder.append(td.text());
        rowBuilder.append(" ");
    }
    System.out.println(rowBuilder.toString());
}

输出为: