簡體   English   中英

使用Jsoup獲取文本塊

[英]Getting a block of text using Jsoup

基本上,我要嘗試的是在URL中輸入歌曲和歌手,然后將我和歌曲的歌詞帶到頁面,然后我將尋找正確的方法來獲取這些歌詞。 我是使用Jsoup的新手。 到目前為止,我一直遇到的問題是我無法弄清楚獲取歌詞的正確方法。 我嘗試過在“ b”之后獲得第一個“ div”,但是它似乎無法解決我的計划。

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();
    }


}

我不知道這在所有歌曲頁面中是否一致,但是在您顯示的頁面中,歌詞與div元素一起出現,其第一個屬性是margin。 如果這是一致的,那么您可以嘗試一下...

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

或者,如果它始終是帶有歌詞的第6個div元素,則可以使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM