使用jsoup解析londonstockexchange页面

kzmpq1sx  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(277)

我正在尝试从以下链接获取数据
https://www.londonstockexchange.com/stock/rio/rio-tinto-plc/fundamentals
为了能够收到损益表,资产负债表等下的一切,但我一直没有成功地得到一个表名,以获得每个类别下的元素。有人知道如何使用jsoup吗?

try {
    final Document document = Jsoup.connect("https://www.londonstockexchange.com/stock/RIO/rio-tinto-plc/fundamentals").get();
    Elements masthead = (document.select("th.table-header th"));
    for (Element row : document.select("table.table-header")) {          
        System.out.println(row.select("table:nth-of-type(2)").text());
    }
} //end of try 
catch (Exception ex) {
    ex.printStackTrace();
}
mctunoxg

mctunoxg1#

该页的数据已嵌入。。或者换一种说法,它是一个单页应用程序,你在错误的地方寻找数据。
另一件事:在我对这个特定的web scrape会话进行了广泛的研究之后,数据中嵌入了一个注解
此数据由富时罗素数据解决方案提供。。。
您可能希望更直接地获取这些数据。
https://www.ftserussell.com/data/equity-data
在我进入这个阶段之前,虽然我成功地提出了一个非常接近的jsonsoup版本,但是需要付出巨大的努力才能获得您想要的数据。因为我真的不知道你是否只想要头条新闻,这是我在决定它足够接近你接管和适应它之前所得到的。
还有一点需要注意:我使用jayway的jsonpath从json中提取数据:

import com.jayway.jsonpath.JsonPath;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.List;

public class LondonStockExchange {

    public static final String URL = "https://www.londonstockexchange.com/stock/RIO/rio-tinto-plc/fundamentals";

    public static void main(String[] args) {
        try {
            final Document document = Jsoup.connect(URL)
                    .ignoreHttpErrors(true)
                    .ignoreContentType(true)
                    .get();
            Elements jsonTag = document.select("#ng-lseg-state");

            String data = jsonTag.get(0).data().replace("&q;", "\"");
            System.out.println(data);

            // 2nd array here likely contains what you want:
            List<String> relevantData = JsonPath.read(data, "$..body.components[*].status.childComponents[*].content");

// These return deeply-nested data structures:
//            List<String> fundamentals = JsonPath.read(data, "$..body.components[*].status.childComponents[*].content.fundamentals");
//            List<String> titleBalanceSheet = JsonPath.read(data, "$..body.components[*].status.childComponents[*].content.titleBalanceSheet");
//            List<String> titleRatios = JsonPath.read(data, "$..body.components[*].status.childComponents[*].content.titleRatios");

            // do stuff with the data
            System.out.println(relevantData);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

如果您使用的是一个好的ide(intellij idea),那么您可以获取json,从控制台输出复制它,将它粘贴到一个.json(scratch)文件中,并立即使用 Code -> Reformat Code 它会很好地为你安排好与最小的努力。然后只需按照您要提取的数据位的键。。。提示: Find 在json中输入所需的数据值,并从中向后构建相关的jsonpath(很像dom导航)。
祝你好运

相关问题