Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract table row data using JSoup returns nothing

Tags:

java

jsoup

I'm trying to extract table row data using JSoup library.But It gives me no result as the output.

Here is my code so far :

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

It will be grateful if any one can suggest me a way to get the out put like below :

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

Thanks.

like image 226
john doe Avatar asked Mar 30 '26 16:03

john doe


1 Answers

The problem is your html. You should add <table> and </table> at the start and end of your html variable, otherwise Jsoup will not parse your html correctly, resulting in your <tbody> converted to <body>, which is why you are not able to select it in your query.

Also, to produce your desired output, use td.html() instead of td.text().

like image 112
Joel Min Avatar answered Apr 02 '26 05:04

Joel Min



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!