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

如何通过Google搜索URL获取结果数量?(Google Apps Script开发)

实现方法

没问题,我来给你分享几个可行的实现思路和代码示例,亲测能用(不过要注意Google的反爬机制哦)

方法一:正则表达式提取(无需额外库)

这种方法不需要引入第三方工具,直接用正则匹配结果统计文本。Google搜索结果里的数量通常在类似约 123,456 条结果的文本里,对应的HTML元素一般带有id="result-stats"。

以下是完整代码示例:

function getSearchResultCount() {
  // 搜索关键词,可替换为你需要的内容
  const searchQuery = "something";
  // 构造搜索URL
  const searchUrl = `https://www.google.com.vn/search?q=${encodeURIComponent(searchQuery)}`;
  
  // 设置请求头,模拟浏览器请求降低被拦截概率
  const options = {
    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"
    }
  };
  
  try {
    // 发送GET请求获取页面内容
    const response = UrlFetchApp.fetch(searchUrl, options);
    const htmlContent = response.getContentText();
    
    // 用正则匹配中文格式的结果数量文本
    const regex = /约 ([\d,]+) 条结果/;
    const match = htmlContent.match(regex);
    
    if (match && match[1]) {
      // 去除逗号并转换为数字格式
      const resultCount = parseInt(match[1].replace(/,/g, ""));
      console.log(`搜索结果数量:${resultCount}`);
      return resultCount;
    } else {
      console.log("未找到结果数量,可能页面结构已变化或请求被拦截");
      return null;
    }
  } catch (error) {
    console.log("请求出错:", error.message);
    return null;
  }
}

方法二:使用Cheerio库解析HTML(更稳定)

如果页面结构小范围调整,正则可能失效,这时可以用Cheerio(类jQuery的HTML解析库)来定位元素,可靠性更高。

步骤如下:

  1. 在Google Apps Script编辑器中,点击「资源」→「库」,输入Cheerio的库ID:1ReeQ6WO8kKNxoaA_O0XEQ589cIrRvEBA9qcWpNqdOP17i47u6N9M5Xh0,选择最新版本后添加为库。
  2. 使用以下代码:
function getSearchResultCountWithCheerio() {
  const searchQuery = "something";
  const searchUrl = `https://www.google.com.vn/search?q=${encodeURIComponent(searchQuery)}`;
  
  const options = {
    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"
    }
  };
  
  try {
    const response = UrlFetchApp.fetch(searchUrl, options);
    const htmlContent = response.getContentText();
    
    // 用Cheerio加载HTML内容
    const $ = Cheerio.load(htmlContent);
    // 获取目标元素的文本内容
    const resultText = $("#result-stats").text().trim();
    
    // 提取数字部分
    const regex = /([\d,]+)/;
    const match = resultText.match(regex);
    
    if (match && match[1]) {
      const resultCount = parseInt(match[1].replace(/,/g, ""));
      console.log(`搜索结果数量:${resultCount}`);
      return resultCount;
    } else {
      console.log("未找到结果数量");
      return null;
    }
  } catch (error) {
    console.log("请求出错:", error.message);
    return null;
  }
}

注意事项

  • 反爬机制:如果频繁发送请求,Google可能返回验证码或直接拦截请求。可以尝试增加请求间隔、更换不同的User-Agent来规避。
  • 页面结构变化:Google的搜索页面结构可能会更新,如果代码突然失效,需要检查result-stats元素是否存在,或者调整正则表达式/选择器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:20:30