문제

The following snippet of code extracts one and only one element, specifically the first element:

  String linkHref = "";
  String linkText = "";
  Elements links = div.getElementsByTag("a");
  for (Element link : links) {
    linkHref = link.attr("href");
    linkText += link.text();              
    break;
  }    

This is really cumbersome code compared to the concise links.get(0) but it has one important feature: It will not throw an IndexOutOfBoundException if Elements is empty. Instead, it will simply leave the strings empty.

I can encapsulate this into my own function but it's hard for me to believe that Jsoup doesn't have such function already (I prefer using library function over "re-inventing the wheel" as much as possible). I searched the documentation but couldn't find any.

Do you know whether such "safe Elements.get(0)" exists in Jsoup?

도움이 되었습니까?

해결책

elements.first() returns the first element from elements, or null if empty.

Also you can use elements.isEmpty() to check if anything matches your selector.

E.g., depending on what you are trying to do:

Element link = div.select("a").first();
if (link != null) {
  String href = link.attr("href");
  String text = link.text();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top