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

如何用Cheerio提取script标签JSON中的指定字段?

使用Cheerio提取script标签中的JSON字段

直接按以下步骤操作就能拿到你要的price和currency字段:

  • 定位目标script标签:利用标签的class和data属性精准匹配,避免误抓其他script标签
  • 提取并清理文本内容:获取标签内的原始文本,去除多余的换行和空格,确保JSON格式合法
  • 解析JSON字符串为对象:用JSON.parse()把清理后的文本转成可操作的JavaScript对象
  • 提取目标字段:从对象中直接解构出需要的字段

完整代码示例

const cheerio = require('cheerio');
// 假设这是你抓取到的HTML内容
const html = `
<script type="application/json" class="js-react-on-rails-component" data-component-name="ItemPriceHeading">
  {
    "price":"29.0",
    "discountedPrice":null,
    "offerPrice":null,
    "totalPrice":"29.0",
    "currency":"PLN"
  }
</script>
`;

// 加载HTML
const $ = cheerio.load(html);

// 定位到目标script标签
const targetScript = $('script.js-react-on-rails-component[data-component-name="ItemPriceHeading"]');
// 提取并清理文本
const rawJson = targetScript.text().trim();

// 解析JSON并提取字段(加try-catch避免格式错误导致崩溃)
try {
  const priceInfo = JSON.parse(rawJson);
  const { price, currency } = priceInfo;
  console.log(`提取结果:价格=${price},货币=${currency}`);
} catch (err) {
  console.error('JSON解析出错,请检查原始数据格式:', err);
}

关键说明

  • 用trim()是因为原script标签内的JSON有大量换行和空格,直接解析可能报错
  • 加上data-component-name的筛选条件,是为了确保只抓对应组件的script标签,避免页面中其他同class的标签干扰
  • 包裹try-catch是防御性编程,防止页面结构变化或JSON格式异常导致代码崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:55:30