因雅虎财经页面更新,如何修改Google Apps Script获取历史价格?
适配雅虎财经页面更新的Google Apps Script代码
原代码因雅虎财经页面结构变更(2021年12月20日起),无法正常抓取历史价格数据,报错TypeError: Cannot read properties of undefined(reading 'prices'),以下是修改后的代码:
function test() { const url = 'https://finance.yahoo.com/quote/CL%3DF/history?p=CL%3DF'; const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText(); const $ = Cheerio.load(res); // 适配新页面结构的解析逻辑 const data = $('script').toArray().reduce((ar, x) => { const c = $(x).get()[0].children; if (c.length > 0) { // 调整正则匹配规则,适配当前页面的脚本格式 const d = c[0].data.trim().match(/window\.YFINANCE\.context = ({[\s\S]+?});/); if (d && d.length === 2) { ar.push(JSON.parse(d[1])); } } return ar; }, []); if (data.length === 0) throw new Error("未获取到数据"); const header = ["date","open","high","low","close","adjclose","volume"]; // 调整数据获取路径,适配新的存储结构 const ar = data[0].context.dispatcher.stores.HistoricalPriceStore.prices.map(o => header.map(h => h === "date" ? new Date(o[h] * 1000) : (o[h] || "")) ); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1"); // 请设置目标工作表名称 sheet.getRange(1, 1, ar.length, ar[0].length).setValues(ar); }
修改说明
- 正则表达式调整:原匹配规则针对旧页面脚本格式,现在改为匹配
window.YFINANCE.context = ({...});格式的脚本内容,适配当前页面的结构 - 数据路径验证:确认当前页面中历史价格数据仍存储在
context.dispatcher.stores.HistoricalPriceStore.prices路径下,若后续页面再次变更需对应调整此路径
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

