You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

谷歌表格批量提取多变体网页指定值的更高效实现方案

高效拉取数据方案

核心改进逻辑

  • 抛弃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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 23:06:08