有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Jsoup不能完全获取原始html代码

我正试图从天才那里得到一些歌词。com(我知道他们有一个api。我正在手动操作。)但我似乎不是每次都得到相同的html字符串。事实上,我把下面的代码放在一个for循环中,它似乎只在50%的时间内工作

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;

public class Fetch_lyrics {
    public static void testing() {
        try {

            String urll = "https://genius.com/In-mourning-debris-lyrics";;
            Document doc = Jsoup.connect(urll).maxBodySize(0).get();
            String text = doc.select("p").first().toString();
            System.out.println(text);

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

我通过doc变量打印了原始html,似乎有大约50%的时间原始html字符串没有包含歌词的<p>类(idk,如果它被称为类或其他东西)。提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    看起来像天才。com为新用户返回不同的内容。当我第一次来的时候,我得到了两种不同的内容,当我在浏览器(Chrome)中清除cookies后,我又去了

    我建议您添加两个选择器以获取所需信息

    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    
    import java.io.IOException;
    
    class Outer {
    
        public static void main(String[] args) {
            try {
                String urll = "https://genius.com/In-mourning-debris-lyrics";
                Document doc = Jsoup.connect(urll).maxBodySize(0).get();
                Element first = doc.selectFirst("p");
                if (first == null) {
                    first = doc.selectFirst("div[class^=Lyrics__Container]");
                }
                if (first != null) {
                    System.out.println(first.text());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }