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:
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.
With XPath expressions it is able to select the elements within the HTML using Jsoup as HTML parser.
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.
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.
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"
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With