使用jsoup解析londonstockexchange页面



我目前正试图从以下链接获取数据

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

该页面的数据已嵌入。。或者换一种说法,它是一个单页应用程序,而你在错误的地方寻找数据。

另一件事:在我对这个特定的网络抓取会话进行了广泛的研究之后,数据中嵌入了一条注释,上面写着

此数据由富时罗素数据解决方案公司提供。。。

您可能更喜欢直接获取此数据。

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导航(。

好运

最新更新