2017-07-27 52 views
0

我是新來的HTML,並試圖通過嘗試從HTML字符串中檢索數據來了解HTML標記。我如何使用Jsoup從html中檢索數據

<li> 
     <div class="item" data-youtube_code="code_for_youtuber" data-feature_code="data" data-feature_url="/movies/Truman"> 
     <div class="title"> 
     <span>the title of the video</span> 
     </div> 
     <div class="image"> 
     <img src="/media/image.png" data-src="http://url_of_image.jpg" alt=""> 
     </div> 
     </div> </li> 

我使用Java Jsoup庫,到目前爲止,我管理使用提取<span>內容:

Document doc = Jsoup.connect("http://www.yesplanet.co.il/movies").get(); 
    System.out.println(doc.html()); 
    Elements elem = doc.select(".item").text();   

我怎樣才能得到其他的東西,如data-youtube_codeimg src

編輯: 例如:

System.out.println("doc...data-youtube_code");//some code that retrieves 
//data-youtube_code. The ouptup will be "code_for_youtuber" 

System.out.println("data-src") 
//some code that retrieves 
//data-src. The ouptup will be "http://url_of_image.jpg" 
+0

你能分享什麼是您預期的輸出? – soorapadman

+0

謝謝你讓我注意到,編輯 – ben

回答

2

您可以簡單地選擇第一個div和屬性獲得價值

Element elements = Jsoup.parse(s).select("div").first(); 
    System.out.println(elements.attr("data-youtube_code")); 

輸出:

code_for_youtuber 

編輯:

Element elements = Jsoup.parse(s).select(".item").first(); 
    System.out.println(elements.attr("data-youtube_code")); 
    Element element1 = elements.select(".image img").first(); 
    System.out.println(element1.attr("data-src")); 

輸出:

code_for_youtuber 
http://url_of_image.jpg 

既然你是初學者,我建議你看看這個link

+0

你也可以請添加一種方式來獲得「img src」內容。由於它不是attr,而是內部標籤attr()將不起作用 – ben