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

使用Google Apps Script+Cheerio抓取GitHub表格返回空数组,求解决

解决Google Apps Script用Cheerio抓取GitHub表格返回空数组的问题

问题原因

你原代码中$('tbody')的选择器未限定目标表格范围,GitHub的Blob页面存在多个tbody元素(如导航栏、侧边栏的表格),而你要抓取的表格被包裹在.markdown-body类容器中,全局查找无法定位到目标单元格,因此返回空数组。

解决方案

方案一:调整Cheerio选择器定位正确表格

修改选择器,先定位到markdown内容区域的表格,再提取单元格内容:

function test2() {
  const url = 'https://github.com/labnol/apps-script-starter/blob/master/scopes.md';
  const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
  const $ = Cheerio.load(res);
  // 限定在markdown内容容器内查找表格单元格
  var data = $('.markdown-body table tbody td').toArray().map(x => $(x).text().trim());
  console.log(data);
}

方案二:直接获取Raw Markdown文件(更高效)

GitHub的Raw URL返回纯Markdown内容,无需解析复杂HTML结构,只需将原URL中的/blob/替换为/raw/即可:

function test2() {
  const url = 'https://raw.githubusercontent.com/labnol/apps-script-starter/master/scopes.md';
  const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
  // 解析Markdown表格
  const rows = res.split('\n').filter(row => row.includes('|'));
  // 跳过表头和分隔线,提取单元格内容
  const data = rows.slice(2).flatMap(row => {
    return row.split('|').slice(1, -1).map(cell => cell.trim());
  });
  console.log(data);
}

内容的提问来源于stack exchange,提问作者Antonio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 20:42:17