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

jQuery动态加载页面IMPORTXML导入为空,求Google Apps Script解决方案

解决Google Sheets IMPORTXML抓取动态页面失败的问题

你遇到的问题是典型的IMPORTXML无法处理JS动态加载内容的场景——它只能解析页面初始返回的静态HTML,而你目标页面的同义词数据是通过jQuery异步加载的,所以返回空结果。

下面提供两种可行的解决方案,其中第一种更简便:

方案1:直接抓取网站的AJAX接口(推荐)

通过浏览器开发者工具的「网络」面板可以发现,该网站的同义词数据实际是通过AJAX请求获取的,接口地址格式为:
https://www.onelook.com/thesaurus/ajax_search?s=你的关键词

这个接口返回JSONP格式的内容,我们可以用Google Apps Script编写自定义函数来解析:

function getOneLookSynonyms(word) {
  const encodedWord = encodeURIComponent(word);
  const url = `https://www.onelook.com/thesaurus/ajax_search?s=${encodedWord}`;
  const response = UrlFetchApp.fetch(url);
  const content = response.getContentText();
  
  // 处理JSONP格式,剥离前后的包装代码
  const jsonContent = content.replace(/^jQuery[\d\.]+\(/, '').replace(/\);$/, '');
  const data = JSON.parse(jsonContent);
  
  // 提取你需要的cluster文本
  const clusters = data.results
    .filter(item => item.cluster)
    .map(item => item.cluster);
  
  return clusters.length > 0 ? clusters : ['无匹配数据'];
}

使用方法:在Google Sheets的单元格中输入=getOneLookSynonyms("active"),即可获取目标数据。

方案2:Google Apps Script渲染动态页面(通用解法)

如果找不到类似的AJAX接口,这种通用方案可以处理所有依赖JS加载的页面:

  1. 打开Google Apps Script编辑器,点击「服务」>「添加服务」,找到并启用Chrome服务;
  2. 点击「资源」>「库」,搜索Cheerio的脚本ID(1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0),添加并启用;
  3. 编写以下脚本:
function scrapeDynamicThesaurus(word) {
  const encodedWord = encodeURIComponent(word);
  const url = `https://www.onelook.com/thesaurus/?s=${encodedWord}`;
  
  // 启动Headless Chrome渲染页面
  const browser = Chrome.createBrowser();
  const page = browser.newPage();
  page.navigate(url);
  page.waitForSelector('td span.cluster'); // 等待目标元素加载完成
  
  const pageHtml = page.content();
  browser.close();
  
  // 用Cheerio解析HTML,提取目标内容
  const $ = Cheerio.load(pageHtml);
  const clusters = $('td:first-child span.cluster')
    .map((index, element) => $(element).text().trim())
    .get();
  
  return clusters.length > 0 ? clusters : ['无匹配数据'];
}

使用方法:在单元格中输入=scrapeDynamicThesaurus("active")即可。

两种方案对比:方案1无需额外配置,执行效率更高;方案2是通用型的动态页面抓取方案,适合更多复杂场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:52:50