简体   繁体   中英

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

I will start off by stating that working with HTML and JSoup for that matter is very foreign to me so if this comes across as a stupid question, I apologize.

What I am trying to achieve with my code is to print the contents from the table on this link https://www.stormshield.one/pve/stats/daviddean/sch into my console in a format like this for each entry:

Wall Launcher 50 grade grade grade grade grade 15% ImpactKnockback 42% Reload Speed 15% Impact Knockback 42% Reload Speed 15% ImpactKnockback 42% Durability

My main issue is pretty much supplying the correct name for the table and the rows, once I can do that the formatting isn't really an issue for me.

This is the code I have tried to use to no avail:

    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());
        }
    }

}

You need to find your table element, and it's head and rows.

Be careful, it is not always the first() element, I add it as an example.

Here is what you need to do:

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());
}

The output is :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM