2014-09-30 86 views
0

基本上我試圖做的是在url中輸入歌曲和藝術家,然後將該歌曲的歌詞帶到頁面,然後我將找到正確的方式得到那些歌詞。我新使用Jsoup。到目前爲止,我遇到的問題是我無法弄清楚歌詞的正確獲取方式。我已經嘗試在「b」之後獲得第一個「div」,但似乎沒有按照我的計劃進行。使用Jsoup獲取文本塊

public static void search() throws MalformedURLException { 

    Scanner search = new Scanner(System.in); 
    String artist; 
    String song; 

    artist = search.nextLine(); 
    artist = artist.toLowerCase(); 
    System.out.println("Artist saved"); 
    song = search.nextLine(); 
    song = song.toLowerCase(); 
    System.out.println("Song saved"); 
    artist = artist.replaceAll(" ", ""); 
    System.out.println(artist); 
    song = song.replaceAll(" ", ""); 
    System.out.println(song); 
    try { 
     Document doc; 
     doc = Jsoup.connect("http://www.azlyrics.com/lyrics/"+artist+"/"+song+".html").get(); 
     System.out.println(doc.title()); 

     for(Element element : doc.select("div")) { 

      if(element.hasText()) { 
       System.out.println(element.text()); 
       break; 
      } 

     } 
    } catch (IOException e){ 
     e.printStackTrace(); 
    } 


} 
+0

請把只是在你的問題上付出很少的努力。你所發佈的只是一個「想要」和一個無法解釋的代碼轉儲,這在坦白的說法上顯得有點不誠實。如果您多花一點時間來描述您的代碼出現了哪些問題,您不清楚哪些具體的事情,我們可能會給您一個更好的答案。我期待着檢查你編輯的問題。祝你好運!另外,請記住,我們都是志願者,所以你的努力使它很容易幫助你**很多**讚賞! – 2014-09-30 00:09:23

+0

請注意,如果這是我的項目,我會深入研究一下我試圖提取的網頁的源代碼,然後逐步嘗試隔離我想要的信息。 – 2014-09-30 00:41:34

回答

0

我不知道這是否一致或不是在所有歌曲頁面中,但在您顯示的頁面中,歌詞會顯示帶有第一個屬性爲margin的div元素。如果這是一致的,你可以嘗試的順序上的東西...

Elements eles = doc.select("div[style^=margin]");   
System.out.println(eles.html()); 

或者,如果它總是與歌詞第六div元素,你可以使用:

Elements eles = doc.select("div"); 
if (eles.size() >= 6) { 
    System.out.println(eles.get(6).html()); 
} 
+0

非常感謝。我正在以我想要的方式獲得它。 – BlackOranges 2014-09-30 15:50:20