Java JSoup:从元素获取文本时出现问题

Java JSoup:从元素获取文本时出现问题,java,jsoup,Java,Jsoup,我在获取div.profileStatLine b中的文本2027pp 97094时遇到问题。这应该是输出,但不是。 URL:页面的某些部分加载了javascript,这就是为什么您无法看到要查找的div 您可以使用浏览器加载页面并在解析之前解释javascript。像这样的图书馆会有帮助的 import java.io.IOException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.

我在获取div.profileStatLine b中的文本2027pp 97094时遇到问题。这应该是输出,但不是。
URL:

页面的某些部分加载了javascript,这就是为什么您无法看到要查找的div

您可以使用浏览器加载页面并在解析之前解释javascript。像这样的图书馆会有帮助的

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;


public class Main {
    public static void main(String[] args) throws Exception {
        Document d=Jsoup.connect("https://osu.ppy.sh/u/charless").get();

        for(Element line : d.select("div.profileStatLine")) {
            System.out.println(d.select("b").text());
        }
    }
}
另一种方法是检查页面中的javascript,并进行与检索数据相同的调用

页面正在从加载配置文件https://osu.ppy.sh/pages/include/profile-general.php?u=4084042&m=0. 看起来u只是用户ID,从页面中提取相对简单:

public static void main(String[] args) throws Exception {
    ChromeDriverManager.getInstance().setup();
    ChromeDriver chromeDriver = new ChromeDriver();
    chromeDriver.get("https://osu.ppy.sh/u/charless");

    Document d = Jsoup.parse(chromeDriver.getPageSource());

    chromeDriver.close();

    for (Element line : d.select("div.profileStatLine")) {
        System.out.println(line.select("b").text());
    }
}

有什么问题吗?没有输出任何东西,补充到问题中。可能是重复的,所以我运行了这个,它工作了。唯一的问题是,我正在制作的程序是一个机器人,它最终将被放到服务器上,所以我想知道这种方法是否仍能在这种环境下工作。Selenium将无头运行,没有任何问题,但对于您正在做的事情来说,它将是相当沉重的。您的另一个选择是对页面进行反向工程,并发现javascript在加载所需内容时所做的调用。
public class ProfileScraper {
    private static final Pattern UID_PATTERN = Pattern.compile("var userId = (\\d+);");

    public static void main(String[] args) throws IOException {
        String uid = getUid("charless");
        Document d = Jsoup.connect("https://osu.ppy.sh/pages/include/profile-general.php?u=" + uid).get();

        for (Element line : d.select("div.profileStatLine")) {
            System.out.println(line.select("b").text());
        }
    }

    public static String getUid(String name) throws IOException {
        Document d1 = Jsoup.connect("https://osu.ppy.sh/u/" + name).get();

        for (Element script : d1.select("script")) {
            String text = script.data();
            Matcher uidMatcher = UID_PATTERN.matcher(text);
            if (uidMatcher.find()) {
                return uidMatcher.group(1);
            }
        }
        throw new IOException("No such character");
    }
}