原正常运行的Yahoo财经Google Apps Script返回空单元格问题
问题描述
此前由tanaike解决的Google Apps脚本原本可正常运行,如今执行后返回空单元格,无错误提示,脚本编辑页面仅显示“Notice Execution completed”。怀疑问题出在最后一行。
原脚本
function pressReleases(code) { var url = 'https://finance.yahoo.com/quote/' + code + '/press-releases' var html = UrlFetchApp.fetch(url).getContentText().match(/root.App.main = ([\s\S\w]+?);\n/); if (!html || html.length == 1) return; var obj = JSON.parse(html[1].trim()); // --- I modified the below script. const { _cs, _cr } = obj; if (!_cs || !_cr) return; const key = CryptoJS.algo.PBKDF2.create({ keySize: 8 }).compute(_cs, JSON.parse(_cr)).toString(); const obj2 = JSON.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(obj.context.dispatcher.stores, key))); var res = obj2.StreamStore.streams["YFINANCE:" + code + ".mega"].data.stream_items[0].title; // --- return res || "No value"; }
(注:脚本中使用的CryptoJS代码取自4.1.1版本)
问题原因与修复方案
Yahoo Finance的页面结构或加密逻辑大概率已更新,导致原脚本中部分数据路径、正则匹配或解密环节失效,且原脚本缺少错误处理,一旦中间步骤失败就会静默返回空值。
修改后的脚本
function pressReleases(code) { try { var url = 'https://finance.yahoo.com/quote/' + code + '/press-releases'; var response = UrlFetchApp.fetch(url); var html = response.getContentText().match(/root.App.main = ([\s\S]+?);\n/); if (!html || html.length < 2) { return "无法匹配到目标数据结构"; } var obj = JSON.parse(html[1].trim()); const { _cs, _cr } = obj; if (!_cs || !_cr) { return "缺少解密所需的_cs或_cr参数"; } const crParsed = JSON.parse(_cr); const key = CryptoJS.algo.PBKDF2.create({ keySize: 8 }).compute(_cs, crParsed).toString(); const encryptedStores = obj.context?.dispatcher?.stores; if (!encryptedStores) { return "找不到加密的stores数据"; } const decrypted = CryptoJS.AES.decrypt(encryptedStores, key); const obj2 = JSON.parse(CryptoJS.enc.Utf8.stringify(decrypted)); const streamKey = "YFINANCE:" + code + ".mega"; const streamData = obj2?.StreamStore?.streams?.[streamKey]?.data?.stream_items; if (!streamData || streamData.length === 0) { return "未找到新闻数据"; } var res = streamData[0].title; return res || "No value"; } catch (e) { return "脚本执行错误: " + e.message; } }
关键修改点
- 新增
try-catch全局异常捕获,将错误信息返回至单元格,避免静默失败 - 调整正则表达式匹配范围,把
[\s\S\w]+?改为[\s\S]+?,适配页面字符变化 - 对每一步数据增加存在性检查,返回明确的提示文本,替代原脚本的空返回
- 使用可选链操作符
?.访问嵌套属性,避免因单个属性缺失导致脚本崩溃
内容的提问来源于stack exchange,提问作者DarkWingDuck
相关产品推荐
相关产品推荐

