如何用Google Apps Script抓取Google Finance当前价格涨跌幅百分比
问题原因
你当前的代码问题出在截取范围的逻辑上:你截取的是当前价格标签<div class="YMlKec fxKbKc">之后的1000个字符,而常规交易时段的涨跌幅数据排布在这个标签之前的DOM结构中,盘后涨跌幅才在这个标签之后,所以你只能抓到盘后数据。
修正方案
直接通过页面涨跌幅对应的固定特征标签定位抓取,修正后的可运行代码如下:
function test() { var url = 'https://www.google.com/finance/quote/AAPL:NASDAQ'; var res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText(); var price, regularChange, afterHoursChange; // 抓取当前价格 const priceTag = '<div class="YMlKec fxKbKc">'; const priceStartIndex = res.indexOf(priceTag) + priceTag.length; const priceEndIndex = res.indexOf('<', priceStartIndex); price = res.substring(priceStartIndex, priceEndIndex); Logger.log('当前价格:' + price); // 抓取常规交易时段涨跌幅,对应页面固定类名标签 const changeTag = '<div class="JwB6zf">'; const changeStartIndex = res.indexOf(changeTag) + changeTag.length; const changeEndIndex = res.indexOf('<', changeStartIndex); regularChange = res.substring(changeStartIndex, changeEndIndex); Logger.log('常规交易涨跌幅:' + regularChange); // 可选:抓取盘后涨跌幅 const afterHoursFlag = 'After Hours'; if (res.indexOf(afterHoursFlag) > -1) { const afterHoursStartIndex = res.indexOf(changeTag, changeEndIndex) + changeTag.length; const afterHoursEndIndex = res.indexOf('<', afterHoursStartIndex); afterHoursChange = res.substring(afterHoursStartIndex, afterHoursEndIndex); Logger.log('盘后涨跌幅:' + afterHoursChange); } }
注意事项
Google Finance的前端类名可能会不定期调整,如果后续抓取失效,可以自行打开页面源码,重新找到涨跌幅对应的标签特征,替换代码里的changeTag值即可。
内容的提问来源于stack exchange,提问作者Newbie
相关产品推荐
相关产品推荐

