简体   繁体   English

我如何从Finance.yahoo.com获取股价,成交量?

[英]How can I get the stock price, volume from finance.yahoo.com?

I am new to Java and I am trying to get the stock price , volume using JSOUP from finance.yahoo.com. 我是Java的新手,我正在尝试使用Finance.yahoo.com上的JSOUP获取股价,交易量。 https://finance.yahoo.com/quote/aapl https://finance.yahoo.com/quote/aapl

The numbers are in the div, table tags. 这些数字在div表标记中。 For instance for AAPL: The Div is a class of "D(ib) W(1/2) ....." Then there is table ,class of W(100%) , then tbody, tr , td and and last is the span tag. 例如对于AAPL:Div是“ D(ib)W(1/2).....”的类。然后是table,类W(100%),然后是tbody,tr,td和last是span标签。

How can I get the value from the span tag, 如何从span标签中获取值,

You have to navigate from a unique point in the HTML structure to the data and try to rely only on "stable" information, ie the label for a field instead of the row count. 您必须从HTML结构中的唯一点导航到数据,并尝试仅依赖“稳定”信息,即字段的标签而不是行数。

For instance let's take the Volume information. 例如,让我们获取音量信息。 Analyze the HTML to get a uniquely identifiable element, ie the table with all the information. 分析HTML以获取唯一可标识的元素,即具有所有信息的表。 In this case it would be the div id="quote-summary" . 在这种情况下,它将是div id="quote-summary"

From there you you could get the table and it's rows ( tr ). 从那里您可以得到表格及其行( tr )。 Now iterate to the table row, that contains a span with the text " Volume ". 现在,迭代到表行,其中包含带有文本“ Volume ”的span

Once you found that row, get either the 2nd td or the next td sibling of the one with the "Volume"- span . 一旦你发现行,无论是获得第二td或下td与“量”的一个兄弟姐妹- span This td contains your span with the Volume value. td包含您的跨度和音量值。

String fieldToFiend = "Volume";

Document doc = Jsoup.connect("https://finance.yahoo.com/quote/aapl").get();

//get the root element
Element quoteSummary = doc.getElementById("quote-summary");
String value = quoteSummary.getElementsByTag("tr")
                           //iterate over the table rows inside
                           .stream()
                           //find the row with the first td/span containing the label
                           .filter(tr -> fieldToFiend.equals(tr.getElementsByTag("span").first().text()))
                           //get the 2nd td and it's span element
                           .map(tr -> tr.getElementsByTag("td")
                                        .first()
                                        .nextElementSibling()
                                        .getElementsByTag("span")
                                        .first()
                                        .text())
                           //get the first match
                           .findFirst()
                           .orElseThrow(NoSuchElementException::new);

System.out.println(value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM