Jsoup 提取URL和链接标题

示例

Jsoup可用于轻松地从网页中提取所有链接。在这种情况下,我们可以使用Jsoup提取我们想要的特定链接,这里h3是页面标题中的链接。我们还可以获取链接的文本。

Document doc = Jsoup.connect("http://stackoverflow.com").userAgent("Mozilla").get();
for (Element e: doc.select("a.question-hyperlink")) {
    System.out.println(e.attr("abs:href"));
    System.out.println(e.text());
    System.out.println();
}

这给出以下输出:

http://stackoverflow.com/questions/12920296/past-5-week-calculation-in-webi-bo-4-0
Past 5 week calculation in WEBI (BO 4.0)?

http://stackoverflow.com/questions/36303701/how-to-get-information-about-the-visualized-elements-in-listview
How to get information about the visualized elements in listview?

[...]

这里发生了什么事:

  • 首先,我们从指定的URL获取HTML文档。此代码还将请求的用户代理标头设置为“ Mozilla”,以便网站提供通常会提供给浏览器的页面。

  • 然后,使用select(...)and for循环获取所有指向Stack Overflow问题的链接,在本例中,链接具有class question-hyperlink。

  • 使用列印每个连结的文字,并使用列印连结的href 。在这种情况下,我们用于获取绝对URL,即。包括域和协议。.text()attr("abs:href")abs: