如何用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
相关产品推荐
相关产品推荐

