我是Java的新手,我試圖從finance.yahoo.com上使用JSOUP獲取股票價格,交易量。 https://finance.yahoo.com/quote/aapl如何從finance.yahoo.com獲得股票價格,交易量?
這些數字在div表格標籤中。例如對於AAPL: DIV是一類「D(ib)W(1/2).....」然後是表W,類(100%),然後tbody,tr,td和最後是span標籤。
我怎樣才能從跨度標籤值,
我是Java的新手,我試圖從finance.yahoo.com上使用JSOUP獲取股票價格,交易量。 https://finance.yahoo.com/quote/aapl如何從finance.yahoo.com獲得股票價格,交易量?
這些數字在div表格標籤中。例如對於AAPL: DIV是一類「D(ib)W(1/2).....」然後是表W,類(100%),然後tbody,tr,td和最後是span標籤。
我怎樣才能從跨度標籤值,
你必須從HTML結構數據的唯一點導航,並嘗試僅僅依靠「穩定」的信息,即標籤的字段而不是行數。
舉例來說,我們來看看Volume信息。分析HTML以獲得唯一可識別的元素,即包含所有信息的表格。在這種情況下,它將是div id="quote-summary"
。
從那裏你可以得到表,它是行(tr
)。現在迭代到表格行,其中包含span
以及文本「卷」。
找到該行後,獲取第二個td
或下一個td
與「音量」 - span
的兄弟。此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);
非常感謝 – amirg
顯示你已經嘗試了什麼,對這個論壇 – azro
Jsoup多前順便說一句,https://stackoverflow.com/questions/38355075/has-yahoo-finance-web-service-disappeared -api-changed-down-temporarily –
Jsoup可以成爲REST/JSON API的良好替代品,特別是HTML應該只是通過JSON提供的相同數據的另一種表示形式(儘管有點冗長)。恕我直言,你的問題是非常有效的,尤其是當雅虎金融webservice似乎被關閉。 –