谷歌表格批量提取多变体网页指定值的更高效实现方案
高效拉取数据方案
核心改进逻辑
- 抛弃IMPORTXML公式,直接在Apps Script后台通过
UrlFetchApp发起网络请求,规避前端公式批量加载的性能问题 - 所有数据先存入二维数组,全部拉取处理完成后一次性写入谷歌表格,大幅减少和表格的交互次数
- 使用正则匹配目标数值,适配非严格规范的HTML结构,比硬编码XPath稳定性更强
优化后代码
function fetchPlayerData() { const sSheet = SpreadsheetApp.getActiveSpreadsheet(); const uniqueSheet = sSheet.getSheetByName("Sheet2"); // 配置参数 const players = [654270, 601000, 335700, 636969, 344585]; const year = 2021; const maxMonth = 12; const requestDelay = 1000; // 每次请求间隔1秒,避免被网站拦截 // 存储结果的二维数组 const resultArr = []; for (let currPlayer = 0; currPlayer < players.length; currPlayer++) { const playerRow = []; const playerId = players[currPlayer]; for (let currMonth = 0; currMonth < maxMonth; currMonth++) { let targetValue = "请求失败"; try { const url = `https://www.trueachievements.com/gamerperiodsummary.aspx?gamerid=${playerId}&year=${year}&month=${currMonth}`; const response = UrlFetchApp.fetch(url, {muteHttpExceptions: true}); const htmlContent = response.getContentText(); // 正则匹配目标数值,适配你提供的HTML结构 const matchReg = /<div class="gs-rd">[\s\S]*?<div>[\s\S]*?<span>(.*?)<\/span>/; const matchResult = htmlContent.match(matchReg); if (matchResult && matchResult[1]) { targetValue = matchResult[1].trim(); } // 加请求间隔 Utilities.sleep(requestDelay); } catch (e) { console.log(`拉取玩家${playerId}${currMonth}月数据失败:${e.toString()}`); } playerRow.push(targetValue); } resultArr.push(playerRow); } // 一次性写入所有数据到表格 if (resultArr.length > 0) { uniqueSheet.getRange(1, 1, resultArr.length, resultArr[0].length).setValues(resultArr); } }
额外优化建议
- 可以给脚本设置定时触发,每月自动运行一次,无需手动操作
- 如果后续玩家数量、月份范围继续扩大,可以拆分请求批次,单次运行不要超过Apps Script 6分钟的运行时长限制
- 正则规则可以根据实际页面结构微调,匹配精度更高
内容的提问来源于stack exchange,提问作者Z792
相关产品推荐
相关产品推荐

