Jsoup:安全 Elements.get(0)
以下代码片段提取一个且仅一个元素,特别是 first 元素:
String linkHref = "";
String linkText = "";
Elements links = div.getElementsByTag("a");
for (Element link : links) {
linkHref = link.attr("href");
linkText += link.text();
break;
}
与简洁的 links.get(0)
相比,这确实是很麻烦的代码,但它有一个重要功能:如果 Elements 为空,它将不会抛出 IndexOutOfBoundException
。相反,它只会将字符串留空。
我可以将其封装到我自己的函数中,但我很难相信 Jsoup 已经没有这样的函数(我更喜欢使用库函数而不是尽可能“重新发明轮子”)。我搜索了文档但找不到任何内容。
你知道Jsoup中是否存在这样的“安全Elements.get(0)
”吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
elements.first() 返回 elements 中的第一个元素,或者 null如果为空。
您也可以使用 elements.isEmpty() 检查是否有匹配项你的选择器。
例如,取决于您想要做什么:
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: