【问题标题】:How to retrieve URL from link tags using Jsoup如何使用 Jsoup 从链接标签中检索 URL
【发布时间】:2016-08-03 16:40:31
【问题描述】:
<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 和链接文本? 我希望它看起来像这样

“链接文本[URL]”

编辑:我只想检索其中的链接

<article itemprop="articleBody"> ... <article>

不是整个页面。另外,我想要其中的所有链接,而不仅仅是一个。

【问题讨论】:

标签: java jsoup


【解决方案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]

【讨论】:

  • 不确定为什么您的第一个解决方案会出现空指针错误。但是,您的第二个解决方案非常有效。非常感谢。
猜你喜欢
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-29
  • 2021-03-29
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多