2016-08-03 64 views
1
<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和链接文本? 我希望它看起来像这样如何使用Jsoup从链接标记中检索URL

“链接文本[URL]”

编辑:我只想检索内

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

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

+1

您是否尝试过使用选择HTTPS ://jsoup.org/cookbook/extracti NG-数据/选择的语法? – Pshemo

+0

是的,那是我遇到的麻烦。特别是使用CSS选择器。 –

+0

你可以发布你的尝试吗?我们大多数人访问Stack Overflow来帮助其他人修正他们的代码,而不是从头开始为他们编写代码,所以通过张贴[你有什么试过](http://mattgemmell.com/what-have-you-tried/)你正在增加您有机会获得体面的回答,并解释您在创建解决方案时所遇到的问题。 – Pshemo

回答

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] 
+0

不确定为什么你的第一个解决方案给出了空指针错误。然而,你的第二个解决方案完美工作非常感谢。 –