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

原IMPORTHTML失效,如何在Google Sheets导入网页card类元素数据?

用Google Apps Script抓取Card元素数据到Google Sheets

实现步骤

  1. 打开脚本编辑器
    在你的Google Sheet里,点击「扩展程序」→「Apps Script」,替换默认代码为以下脚本:
function fetchConsensusData() {
  const targetUrl = "https://www.marketscreener.com/quote/stock/APPLE-INC-4849/consensus/";
  const htmlContent = UrlFetchApp.fetch(targetUrl).getContentText();
  
  // 解析HTML,定位class含card的元素
  const xmlDoc = XmlService.parse(htmlContent);
  const rootElem = xmlDoc.getRootElement();
  const ns = rootElem.getNamespace();

  // 筛选所有带card类的元素
  const cardElements = rootElem.getDescendants().filter(elem => {
    const classAttr = elem.getAttribute("class");
    return classAttr && classAttr.getValue().includes("card");
  });

  // 提取card内的有效文本,整理成表格格式
  const outputData = [];
  cardElements.forEach(card => {
    const textNodes = card.getDescendants()
      .filter(node => node.getType() === XmlService.ContentType.TEXT)
      .map(node => node.getText().trim())
      .filter(text => text.length > 0);
    if (textNodes.length) outputData.push(textNodes);
  });

  // 将数据写入当前工作表的A1起始位置
  const activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  if (outputData.length) {
    activeSheet.getRange(1, 1, outputData.length, outputData[0].length).setValues(outputData);
  }
}
  1. 适配网站DOM结构
    上述是通用模板,需根据目标网站实际HTML结构微调:
  • 可添加Logger.log(htmlContent)打印原始HTML,查看card元素内部的标签层级(比如是否用<div>、<li>承载数据)
  • 若需提取特定子元素(如card内的标题、数值),可修改筛选逻辑,比如只提取带特定类名的<span>或<p>元素文本
  1. 运行与授权
    保存脚本后点击运行,首次运行需完成权限授权(按页面提示操作),运行成功后数据会自动写入当前工作表。

  2. 定时刷新(可选)
    如需定期更新数据,点击「编辑」→「当前项目的触发器」,添加时间驱动触发器,设置自动运行的频率(如每天一次)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:03:30