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