Search code examples
javajsoup

Find element with given text using jsoup


I have a table like in this fiddle. I need to find data related to the row which contains given text.

table

For example, by providing 1707, I need to get all data in table row which contains 1707. So output should be as below.

Tuesday 2014-08-05 1707 33 43 47 52 image text

Currently I'm accessing data on html page as below.

    Document doc;
    try {
        doc = Jsoup
                .connect("url here").timeout(300000).userAgent("Mozilla").get();

        Element table = doc.select("table#customers").first();          
        if (table != null) {
            Iterator<Element> iterator = table.select("td").iterator();
            while (iterator.hasNext()) {
                System.out.println("Day : " + iterator.next().text());
                System.out.println("Date : " + iterator.next().text());                 
                System.out.println("Draw : " + iterator.next().text());                 
                System.out.println("No1 : " + iterator.next().text());
                System.out.println("No2 : " + iterator.next().text());
                System.out.println("No3 : " + iterator.next().text());
                System.out.println("No4 : " + iterator.next().text());
                System.out.println("Symbol : " + iterator.next().text());
                System.out.println("Non : " + iterator.next().text());
            }
        } else {
            System.out
                    .println("No results were found according to search criteria.");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The above code return all data on table. But I need to get data related to given text.

How could I achieve this?


Solution

  • As shown in jsoup documentation you can use the pseudo-selector :contains(text):

    table.select("tr:contains(1707) td")
    

    You can try it here