Java HTML / XML How to - Get elements by class in HTML with Jsoup








Question

We would like to know how to get elements by class in HTML with Jsoup.

Answer

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/*from ww  w  . j  av  a2s  .c om*/
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        Document doc = Jsoup.connect("http://www.your server.com/").get();
        Elements tableRows = doc.select("tr");
        for (Element row : tableRows) {
            Elements cls1 = row.getElementsByClass("cls1");
            Elements cls2 = row.getElementsByClass("cls2");
            Elements cls3 = row.getElementsByClass("cls3");

            if (!cls1.isEmpty() && !cls2.isEmpty() && !cls3.isEmpty()) {
                System.out.println(cls1.get(0).text());
                System.out.println(cls2.get(0).text());
                System.out.println(cls3.get(0).text());
            }
        }
    }
}