[英]How to use xpath to extract the price of a stock from google finance?
[英]Importing stock price from Yahoo Finance in Google sheets
我正在嘗試在我的 Google 表格中從 Yahoo Finance 導入一些新加坡股票價格。 我正在使用代碼
=IMPORTXML("https://finance.yahoo.com/quote/" & A2,"//*[@id='quote-header-info']/div[3]/div[1]/div/span[1]")
並將股票代碼放在 A2 中。 它適用於一些新交所股票,但不適用於其他股票。 申請 STI 成分,我得到了類似的東西
股票代碼 | 價格 |
---|---|
D05.SI | 28.4 |
O39.SI | 11.61 |
U11.SI | #不適用 |
Z74.SI | 2.41 |
J36.SI | #不適用 |
A17U.SI | 3.05 |
C38U.SI | #不適用 |
Y92.SI | #不適用 |
S68.SI | #不適用 |
C31.SI | 3.75 |
... | ... |
我檢查了 U11.SI 和 J36.SI,價格元素的 XPATH 與 D05.SI 相同。 以下是 Google 表格的鏈接
https://docs.google.com/spreadsheets/d/1Tp9leC43J1W3Jun3Z23K51zmbkZRhPOcM60ffBPOs90/edit?usp=sharing
任何人都可以闡明這里出了什么問題嗎? 謝謝!
您可以使用 Google Apps 腳本輕松地從 Yahoo Finance 中提取數據。 在 Apps 腳本中,您可以定義一個 function 來從任何 web 頁面檢索數據,然后解析 HTML Z78366DZ1D6389DZ183E6221F6389DZ。
function yahooF() {
const ticker = 'AAPL';
const url = `https://finance.yahoo.com/quote/${ticker}?p=${ticker}`;
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
const contentText = res.getContentText();
const price = contentText.match(/<fin-streamer(?:.*?)data-test="qsp-price"(?:.*)>(\d+\.\d+)<\/fin-streamer>/);
console.log(price[1]);
return price[1];
}
在上面的代碼片段中,使用UrlFetchApp
檢索了 Yahoo Finance 關於 Apple 股票的頁面。 然后使用正則表達式提取代碼的價格,並且可以使用定義的=yahooF()
function 在 Google 表格中獲取 Apple 的股票價格。
我在一篇關於 Medium 的文章中更深入地解釋了這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.