【问题标题】:Get information from Yahoo Finance从雅虎财经获取信息
【发布时间】:2021-02-05 23:49:02
【问题描述】:
【问题讨论】:
标签:
google-sheets
yahoo-finance
【解决方案1】:
尝试:
=INDEX(IMPORTXML(A1, "//tr"), 9, 2)
或:
=INDEX(QUERY(TO_TEXT(IMPORTXML(A1, "//tr")),
"select Col2 where Col1 = 'Market Cap'", 0))
但是!
这样你只能得到旧值。要获得新的,您需要使用脚本:
function YAHOO(url) {
const res = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
const tables = [...res.getContentText().matchAll(/(<table[\w\s\S]+?<\/table>)/g)];
if (tables.length < 2) return "No tables. Please confirm URL again.";
const values = tables.reduce((ar, [,table]) => {
if (table) {
const root = XmlService.parse(table).getRootElement();
const temp = root.getChild("tbody", root.getNamespace()).getChildren().map(e => e.getChildren().map(f => isNaN(f.getValue()) ? f.getValue() : Number(f.getValue())));
ar = ar.concat(temp);
}
return ar;
}, []);
return values[0].map((_, i) => values.map(r => r[i]));
}
和公式:
=INDEX(YAHOO(A1), 2, 9)
额外阅读:https://stackoverflow.com/a/65914858/5632629
【解决方案2】:
您可以尝试使用完整的 XPath:
=IMPORTXML(A1,"/html/body/div[1]/div/div/div[1]/div/div[3]/div[1]/div/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[1]/td[2]/span")
或者你可以试试vlookup():
=vlookup("Market Cap", IMPORTXML(A1,"//tr"),2,0)