Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup Get Element only if it exists

I am looking for a possibility to get an element only if it exists. Otherwise I get an error, because it does not exists.

Following case which I have:

  • Table with "tr" tags (e.g. 3).
  • Code is looking into every "tr" to search a specific data. If not exists, it looks for the next "tr" element. Here, if there is no more "tr" element, it occurs an error.

What I have:

Element e = doc.getElementsByClass("table table-striped table-hover nofooter-").first();
Element tbody = e.select("tbody").first();
int j = 0;

while(tbody != null){
   Element tr = tbody.select("tr").get(j); //Look for the next "tr" --> HERE: error, because there is no more "tr", if string "A" not found in all existing "tr"s.
   if(tr != null){
      if(string == "A"){
         //Do something
      }
      j = j+1; //Increment for looking for the next "tr"
   }
}

So I need a construct to check, if a "next" "tr" element exists.

like image 205
Giovanni19 Avatar asked Dec 27 '16 23:12

Giovanni19


People also ask

Can we use XPath in jsoup?

With XPath expressions it is able to select the elements within the HTML using Jsoup as HTML parser.

What is jsoup element?

A HTML element consists of a tag name, attributes, and child nodes (including text nodes and other elements). From an Element, you can extract data, traverse the node graph, and manipulate the HTML.

What does jsoup clean do?

clean. Creates a new, clean document, from the original dirty document, containing only elements allowed by the safelist. The original document is not modified. Only elements from the dirty document's body are used.


1 Answers

The problem is that you are chaining multiple methods together when you do:

tbody.select("tr").get(j);

If the first part of the statement, tbody.select("tr"), returns nothing, you will get an error when you try to call get(j), since you can't call methods on an empty object.

Instead, break your methods up on to separate lines.

First do tbody.select("tr") and save that result into a separate elements variable. Then, add a check to see if the elements variable is empty. You can do that by either doing !elements.isEmpty() or elements.size() > 0. Once you determine that the variable is not empty, you can call .get(j) method on the variable and set the Element tr value.

The resulting code will look something like the following:

while(tbody != null){

    Elements elements = tbody.select("tr");

    if(!elements.isEmpty()){

        Element tr = temp.get(j);

        if(tr != null){
            if(string == "A"){
                //Do something
            }
            j = j + 1; //Increment for looking for the next "tr"
        }

    }

}
like image 119
Tot Zam Avatar answered Oct 06 '22 08:10

Tot Zam