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

如何使用Cheerio提取script标签内JSON中的datePublished字段

如何用Cheerio提取script标签内JSON中的发布时间字段

针对这类嵌套在script标签JSON结构里的发布时间,可以按以下步骤操作:

  • 先定位目标script标签:这类结构化数据一般在type="application/ld+json"的script标签中,用Cheerio选中它
  • 提取标签内的原始文本,清理掉多余空白字符
  • 把文本解析成JSON对象,再从中提取datePublished字段
  • 加上异常处理,避免找不到标签或解析失败导致程序报错

示例代码如下:

const cheerio = require('cheerio');
const html = '你的页面HTML内容'; // 替换为实际抓取到的页面HTML

const $ = cheerio.load(html);
// 选中目标script标签
const scriptContent = $('script[type="application/ld+json"]').html();

if (scriptContent) {
  try {
    // 解析JSON
    const jsonData = JSON.parse(scriptContent.trim());
    // 处理可能的数组情况(部分页面的ld+json是数组格式)
    const targetData = Array.isArray(jsonData) ? jsonData.find(item => item.datePublished) : jsonData;
    const publishedTime = targetData?.datePublished;
    
    if (publishedTime) {
      console.log('发布时间:', publishedTime);
    } else {
      console.log('未找到datePublished字段');
    }
  } catch (err) {
    console.log('JSON解析失败:', err);
  }
} else {
  console.log('未找到目标script标签');
}

说明:有些网站的application/ld+json内容是数组形式,所以代码里加了数组判断,确保能正确找到包含datePublished的对象。如果是单个对象,直接取属性即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 02:44:56