Eva*_*ler 0 google-sheets web-scraping google-apps-script yahoo-finance google-sheets-formula
我正在按照以下教程将股票期权数据导入 Google 工作表。
https://www.youtube.com/watch?v=Be7z9YeeVY0&ab_channel=daneshj
以下公式将把雅虎财经的数据导入到工作表中:
=iferror(TRANSPOSE(IMPORTXML(CONCATENATE("https://finance.yahoo.com/quote/",A2,"?p=",A2),"//tr")),"You have to add a contract name in column A")
Run Code Online (Sandbox Code Playgroud)
乍一看,一切看起来都很好,因为它似乎是从网页上拉回数据;然而,所有的值都是不正确的。
本示例中从中提取数据的 URL 如下。请注意,数据经常变化。
https://finance.yahoo.com/quote/NKLA220121C00002500?p=NKLA220121C00002500
这些数字不仅在这个特定示例中是错误的,而且每次都是错误的,并且误差范围足够大,我不认为这是由于 IMPORTXML 缓存页面造成的。我已经搜索了网页的 HTML 源代码,但在任何地方都找不到 IMPORTXML 中的值。
=iferror(TRANSPOSE(IMPORTXML("https://finance.yahoo.com/quote/NKLA220121C00002500?p=NKLA220121C00002500","//tr")),"You have to add a contract name in column A"),我可以确认你的问题的情况相同。从这些情况来看,在这个答案中,我想建议使用Google Apps Script。
请将以下脚本复制并粘贴到 Google 电子表格的容器绑定脚本中并保存。并请放入=SAMPLE("https://finance.yahoo.com/quote/NKLA220121C00002500?p=NKLA220121C00002500")牢房。这样就返回了结果。在本例中,Google Apps 脚本用作自定义函数。
function SAMPLE(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]));
}
Run Code Online (Sandbox Code Playgroud)
我测试了这个示例脚本的 URL https://finance.yahoo.com/quote/NKLA220121C00002500?p=NKLA220121C00002500。当 URL 更改时,脚本可能无法使用。所以请小心这一点。届时,请分析每个HTML数据并修改脚本。
| 归档时间: |
|
| 查看次数: |
1043 次 |
| 最近记录: |