Google Sheets中IMPORTHTML函数导入表格报错“导入内容为空”求助
问题:Google Sheets IMPORTHTML导入Macrotrends表格失败,返回“Imported content is empty.”
我尝试从Macrotrends网站导入苹果公司的利润表到Google Sheets,使用公式:=IMPORTHTML("https://www.macrotrends.net/stocks/charts/AAPL/apple/income-statement", "table", 1)
但结果显示错误:“Imported content is empty.”
怀疑网站表格不符合Google Sheets识别的标准HTML格式,但缺乏HTML相关经验,求解决方法。
解决方法
- 验证表格索引:部分网站的表格可能存在嵌套或索引并非从1开始,尝试修改公式中的第三个参数,依次测试
2、3等数值,比如:=IMPORTHTML("https://www.macrotrends.net/stocks/charts/AAPL/apple/income-statement", "table", 2) - 用Google Apps Script绕过反爬:Macrotrends可能拦截了Google Sheets的默认请求,可通过自定义脚本模拟浏览器请求抓取数据:
- 打开Google Sheets,点击「扩展程序」→「Apps 脚本」
- 删除默认代码,粘贴以下脚本:
function getMacroTrendsData(url) { const requestOptions = { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } }; const rawResponse = UrlFetchApp.fetch(url, requestOptions); const pageHtml = rawResponse.getContentText(); // 定位页面中的第一个表格 const tableStartPos = pageHtml.indexOf('<table'); const tableEndPos = pageHtml.indexOf('</table>', tableStartPos) + 8; const tableHtml = pageHtml.slice(tableStartPos, tableEndPos); // 解析表格为二维数组 const xmlDoc = XmlService.parse(tableHtml); const rootElement = xmlDoc.getRootElement(); const tableRows = rootElement.getChildren('tr'); const resultData = []; tableRows.forEach(row => { const rowCells = row.getChildren(); const rowContent = []; rowCells.forEach(cell => { rowContent.push(cell.getText().trim()); }); resultData.push(rowContent); }); return resultData; }- 保存脚本后,回到表格单元格输入:
=getMacroTrendsData("https://www.macrotrends.net/stocks/charts/AAPL/apple/income-statement")
- 手动导出导入:如果代码方法太复杂,直接在Macrotrends页面找到表格的导出选项(一般支持CSV/Excel格式),下载文件后上传到Google Sheets完成导入。
内容的提问来源于stack exchange,提问作者Mr. Golden
相关产品推荐
相关产品推荐

