简体   繁体   English

Jsoup仅在元素存在的情况下获取

[英]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 (eg 3). 带有“tr”标签的表(例如3)。
  • Code is looking into every "tr" to search a specific data. 代码正在调查每个“tr”以搜索特定数据。 If not exists, it looks for the next "tr" element. 如果不存在,则查找下一个“tr”元素。 Here, if there is no more "tr" element, it occurs an error. 这里,如果没有更多“tr”元素,则会发生错误。

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. 如果存在“next”“tr”元素,我需要一个构造来检查。

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. 如果语句的第一部分tbody.select("tr")没有返回任何内容,则在尝试调用get(j)时会出现错误,因为您无法在空对象上调用方法。

Instead, break your methods up on to separate lines. 相反,打破你的方法分开线。

First do tbody.select("tr") and save that result into a separate elements variable. 首先执行tbody.select("tr")并将结果保存到单独的elements变量中。 Then, add a check to see if the elements variable is empty. 然后,添加一个检查以查看elements变量是否为空。 You can do that by either doing !elements.isEmpty() or elements.size() > 0 . 您可以通过执行!elements.isEmpty()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. 一旦确定变量不为空,就可以对变量调用.get(j)方法并设置Element tr值。

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"
        }

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM