我正试图在谷歌表单中从雅虎金融导入一些新加坡股票价格。我正在使用代码
=IMPORTXML("https://finance.yahoo.com/quote/" & A2,"//*[@id='quote-header-info']/div[3]/div[1]/div/span[1]")
并将股票代码放入A2。它适用于一些SGX股票,但不适用于其他股票。应用于STI成分,我得到了类似的东西
报价 | |
---|---|
D05.SI | 28.4 |
O39.SI | 11.61 |
U11.SI | #N/A |
Z74.SI | 2.41 |
J36.SI | #N/A |
A17U.SI | 3.05 |
C38U.SI | #N/A |
Y92.SI | #N/A |
S68.SI | #N/A |
C31.SI | 3.75 |
使用谷歌应用程序脚本,您可以很容易地从雅虎金融获取数据。在Apps脚本中,您可以定义一个函数来从任何网页检索数据,然后解析HTML输出。
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
检索的。然后使用正则表达式提取股票代码的价格,通过使用定义的=yahooF()
函数可以在谷歌表单中获得苹果的股价。
我在Medium上的一篇文章中对此进行了更深入的解释。