2016-04-14 115 views
1

我想提取jsoup中给定元素内的链接。在这里我做了什么,但它不工作:Java jsoup链接提取

Document doc = Jsoup.connect(url).get(); 
     Elements element = doc.select("section.row"); 
     Element s = element.first(); 
     Elements se = s.getElementsByTag("article"); 


      for(Element link : se){ 
       System.out.println("link :" + link.select("href")); 
      } 

下面是HTML: enter image description here

我试图做的事情是让所有withing文章类的链接。我认为也许首先我必须选择section =“row”部分,然后在那之后从文章类中获取链接,但是我无法使其工作。

+0

你会得到什么结果? – GHajba

+0

上面的代码给出了任何结果,当我试图打印元素时,它向我展示了与图像 – imoteb

回答

1

试试这个。

Document doc = Jsoup.connect(url).get();  

    Elements section = doc.select("#main"); //select section with the id = main 
    Elements allArtTags = section.select("article"); // select all article tags in that section 
    for (Element artTag : allArtTags){ 
     Elements atags = artTag.select("a"); //select all a tags in each article tag 
     for(Element atag : atags){ 
      System.out.println(atag.text()); //print the link text or 
      System.out.println(atag.attr("href"));//print link 
     } 
    } 
+0

一样的内容,谢谢 – imoteb

+1

您不需要那些嵌套的循环和选择器。你可以做'元素atags = doc.select(“#main article a”)'。 –

0

我在我的项目之一使用此:

final Elements elements = doc.select("div.item_list_section.item_description"); 

你必须得到你想要从中提取链接的元素。

private static ... inspectElement(Element e) { 
     try { 
      final String name = getAttr(e, "a[href]"); 
      final String link = e.select("a").first().attr("href"); 
      //final String price = getAttr(e, "span.item_price"); 
      //final String category = getAttr(e, "span.item_category"); 
      //final String spec = getAttr(e, "span.item_specs"); 
      //final String datetime = e.select("time").attr("datetime"); 

      ... 
     } 
     catch (Exception ex) { return null; } 
} 

private static String getAttr(Element e, String what) { 
    try { 
     return e.select(what).first().text(); 
    } 
    catch (Exception ex) { return ""; } 
}