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

如何用Cheerio将指定class节点及其子元素转为对象并存入数组?

用Cheerio提取col-item-shopdetail节点并转为可便捷访问的对象数组

嘿,我来帮你捋清楚怎么高效搞定这个需求!不用再分两次循环存数据啦,咱们一次遍历就能把所有目标节点转成对象数组,还能直接通过属性访问你要的item-inverserate这类数据。

核心思路

直接遍历每一个col-item-shopdetail节点,把当前节点下的所有子元素数据(比如店铺名、逆向率、地址等)一次性提取出来,组装成一个对象;最后把所有对象收集到数组里。这样既不会出现索引对应错误,代码也更简洁。

先模拟下你的HTML结构(方便示例)

假设你的目标HTML片段长这样:

<div class="col-item-shopdetail">
  <h3 class="shop-name">XX便利店</h3>
  <div class="item-inverserate">0.85</div>
  <p class="shop-address">XX街道123号</p>
</div>
<div class="col-item-shopdetail">
  <h3 class="shop-name">YY生鲜店</h3>
  <div class="item-inverserate">0.92</div>
  <p class="shop-address">YY路456号</p>
</div>

Cheerio实现代码

const cheerio = require('cheerio');
// 这里的html是你抓取到的完整网页内容
const $ = cheerio.load(html);

// 提取所有目标节点并转为对象数组
const shopDetails = $('.col-item-shopdetail').map((index, element) => {
  // 把当前DOM元素转为Cheerio对象,方便操作子元素
  const $currentShop = $(element);
  return {
    // 提取店铺名称,trim()去除前后空格
    shopName: $currentShop.find('.shop-name').text().trim(),
    // 提取逆向率,转成数字类型(如果需要的话)
    inverseRate: parseFloat($currentShop.find('.item-inverserate').text().trim()),
    // 提取店铺地址
    shopAddress: $currentShop.find('.shop-address').text().trim()
    // 其他你需要的字段,都可以在这里继续添加
  };
}).get(); // 把Cheerio返回的类数组转成真正的JavaScript数组

怎么访问数据

现在shopDetails就是一个包含所有店铺数据的数组,你可以这样轻松访问:

  • 获取第一个店铺的逆向率:shopDetails[0].inverseRate
  • 遍历所有店铺数据:
shopDetails.forEach(shop => {
  console.log(`店铺:${shop.shopName},逆向率:${shop.inverseRate},地址:${shop.shopAddress}`);
});

补充:完整的网页抓取流程

如果还没搞定网页数据抓取,给你一个完整的流程示例(用axios发送请求):

const axios = require('axios');
const cheerio = require('cheerio');

async function fetchAndParseShopData() {
  try {
    // 1. 发送HTTP请求获取网页内容
    const response = await axios.get('你要抓取的网页URL');
    // 2. 用Cheerio加载网页内容
    const $ = cheerio.load(response.data);
    // 3. 提取数据(就是上面的代码)
    const shopDetails = $('.col-item-shopdetail').map((index, element) => {
      const $currentShop = $(element);
      return {
        shopName: $currentShop.find('.shop-name').text().trim(),
        inverseRate: parseFloat($currentShop.find('.item-inverserate').text().trim()),
        shopAddress: $currentShop.find('.shop-address').text().trim()
      };
    }).get();
    // 4. 处理或输出数据
    console.log('提取到的店铺数据:', shopDetails);
  } catch (error) {
    console.error('抓取或解析失败:', error);
  }
}

// 执行函数
fetchAndParseShopData();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:59:24