the following snippet of code extracts 1 , 1 element, first element:
string linkhref = ""; string linktext = ""; elements links = div.getelementsbytag("a"); (element link : links) { linkhref = link.attr("href"); linktext += link.text(); break; }
this cumbersome code compared concise links.get(0)
has 1 important feature: not throw indexoutofboundexception
if elements empty. instead, leave strings empty.
i can encapsulate own function it's hard me believe jsoup doesn't have such function (i prefer using library function on "re-inventing wheel" as possible). searched documentation couldn't find any.
do know whether such "safe elements.get(0)
" exists in jsoup?
elements.first() returns first element elements, or null if empty.
also can use elements.isempty() check if matches selector.
e.g., depending on trying do:
element link = div.select("a").first(); if (link != null) { string href = link.attr("href"); string text = link.text(); }
Comments
Post a Comment