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

如何在Google Apps Script中用Cheerio提取首个HTML表格的数组格式数据

调整后完整代码

function test() {
  const url = 'https://finviz.com/quote.ashx?t=AFRM';
  const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
  const page = Cheerio.load(res);

  // 同时满足仅取第一个表格、返回数组两个需求
  var tableValue = page('table:has(.snapshot-td2):first .snapshot-td2')
    .map((index, element) => page(element).text().trim())
    .get();
  console.log(tableValue);
}

调整说明

  • 仅提取第一个表格数据:通过table:has(.snapshot-td2):first选择器,先匹配所有包含snapshot-td2类单元格的表格,再用:first伪类只保留第一个匹配的表格,仅查询该表格内的单元格,不会读取第二个表格的内容。
  • 输出数组格式:调用Cheerio的map()方法遍历所有匹配到的单元格,逐个提取文本并去除首尾空白后,调用get()方法将Cheerio对象集合转换为原生JavaScript数组,最终得到按单元格顺序排列的文本数组。

如果你的Cheerio版本不支持:has伪类,可以使用兼容性更好的写法:

// 先找到第一个包含.snapshot-td2的表格
const firstTable = page('.snapshot-td2').closest('table').first();
// 提取该表格内所有.snapshot-td2的文本为数组
const tableValue = firstTable.find('.snapshot-td2').map((i, el) => page(el).text().trim()).get();

页面结构参考

页面结构示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:36:04