我有以下 jsFiddle
我尝试使用 JSoup 获取第 238 行超链接的 href
字符串的值:
<a href="/chain/admin/config/editRepository.action?planKey=AB-CSD&repositoryId=28049450">
因此,期望的结果是获得一个值为:
/chain/admin/config/editRepository.action?planKey=AB-CSD&repositoryId=28049450
这是我的代码:
Document doc = Jsoup.connect("http://myapp.example.com/fizz.html").get()
Elements elems = doc.getElementsByAttributeValueContaining("href", "repositoryId")
当我运行此命令时,elems
的值为空:为什么,我需要做什么才能获得所需的字符串?
最佳答案
在这种情况下,getElementsByAttributeValueContaining()
方法将返回多个值,因为许多 hrefs
具有repositoryId。如果您特别关注第 238 行,那么 a
包含在具有 item item-default
类的 li
内。其中只有一个这样的 li
和两个 a 标签。就拿第一个吧
String html = "<li class=\"item item-default\" data-item-id=\"28049450\" id=\"item-28049450\">"
+ "<a href=\"/chain/admin/config/editRepository.action?planKey=AB-CSD&repositoryId=28049450\">"
+ "<h3 class=\"item-title\">MCAppRepo <span class=\"item-default-marker grey\">(default)</span></h3>"
+ "</a>"
+ "<a href=\"/chain/admin/config/confirmDeleteRepository.action?planKey=AB-CSD&repositoryId=28049450\" class=\"delete\" title=\"Remove repository\">"
+ "<span class=\"assistive\">Delete</span>"
+ "</a>"
+ "</li>";
Document doc = Jsoup.parse(html);
Elements elems = doc.select("li.item.item-default > a");
System.out.println(elems.first().attr("href"));
关于java - 如何使用JSoup获取超链接href?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806691/