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

如何使用Google Sheets IMPORTXML仅导入指定样式的内容?

在Google Sheets中用IMPORTXML筛选特定
  • 元素的方法
  • 直接用XPath筛选(推荐)

    Google Sheets的IMPORTXML支持XPath条件筛选,你可以用以下XPath表达式直接定位符合要求的<li>元素:

    /html/body/div[1]/div/article/div/div[1]/div/div/div[3]/div/div/div[2]/div[1]/ul/li[.//*[contains(@style,'color:red')] or .//strong]
    

    表达式说明:

    • .//*[contains(@style,'color:red')]:匹配当前<li>下任意层级、style属性包含color:red的元素
    • .//strong:匹配当前<li>下任意层级的<strong>标签
    • or:逻辑或,满足任一条件的<li>都会被选中

    使用示例:

    在Google Sheets单元格中输入:

    =IMPORTXML("你的目标页面URL", "/html/body/div[1]/div/article/div/div[1]/div/div/div[3]/div/div/div[2]/div[1]/ul/li[.//*[contains(@style,'color:red')] or .//strong]")
    

    备选方案:Google Apps Script(若XPath失效)

    如果目标页面是动态渲染(比如依赖JS加载内容),IMPORTXML可能无法抓取到数据,这时可以用Google Apps Script实现自定义筛选:

    1. 打开目标表格,点击「扩展程序」→「Apps脚本」
    2. 替换默认代码为以下内容:
    function getFilteredListItems(url) {
      const response = UrlFetchApp.fetch(url);
      const html = response.getContentText();
      const doc = XmlService.parse(html);
      const root = doc.getRootElement();
      
      const xpath = "/html/body/div[1]/div/article/div/div[1]/div/div/div[3]/div/div/div[2]/div[1]/ul/li[.//*[contains(@style,'color:red')] or .//strong]";
      const namespace = XmlService.getNamespace("http://www.w3.org/1999/xhtml");
      const items = XmlService.getNamespaceManager().getXPathResult(root, xpath, namespace, XmlService.XPathResultType.ORDERED_NODE_SNAPSHOT_TYPE);
      
      const result = [];
      for (let i = 0; i < items.getLength(); i++) {
        const liText = XmlService.getRawText(items.snapshotItem(i)).trim();
        if (liText) result.push([liText]);
      }
      
      return result;
    }
    
    1. 保存脚本后,回到表格单元格输入:
    =getFilteredListItems("你的目标页面URL")
    

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

    相关产品推荐
    方舟 Agent Plan

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

    最近更新时间:2026.08.14 03:05:25