如何使用Jsoup从链接标记中检索URL

时间:2016-08-03 16:40:32

标签: java jsoup

<article itemprop="articleBody">
  <p channel="wp.com" class="interstitial-link">
     <i>
        [<a href="www.URL.com" shape="rect">Link Text</a>]
     </i>
  </p>
<article>

如何从此HTML文档中检索带有Jsoup的URL和链接文本? 我希望它看起来像这样

“链接文字[网址]”

编辑:我只想检索

中的链接
<article itemprop="articleBody"> ... <article>

不是整个页面。此外,我想要所有链接,而不仅仅是一个。

1 个答案:

答案 0 :(得分:1)

    // connect to URL and retrieve source code as document
    Document doc = Jsoup.connect(url).get();

    // find the link element in the article
    Element link = doc
            .select("article[itemprop=articleBody] p.interstitial-link i a")
            .first();

    // extract the link text
    String linkText = link.ownText();

    // extract the full url of the href
    // use this over link.attr("href") to avoid relative url
    String linkURL = link.absUrl("href");


    // display
    System.out.println(
            String.format(
                    "%s[%s]", 
                    linkText,
                    linkURL));

详细了解CSS Selectors

你也可以像这样迭代文章中的每个链接:

    for (Element link : doc.select("article[itemprop=articleBody] a")) {
        String linkText = link.ownText();
        String linkURL = link.absUrl("href");
        System.out.println(
                String.format(
                        "%s[%s]", 
                        linkText,
                        linkURL));
    }

输出

Link Text[http://www.URL.com]