Cheerio HTML Metadata Extraction

Parse fetched HTML with Cheerio to extract OpenGraph metadata, clean text, and attribute values without executing any page scripts.

JavascriptData Fetching

Code

snippet
import * as cheerio from 'cheerio';

const html = await fetch('https://example.com/article')
  .then((r) => r.text());

const $ = cheerio.load(html);

const metadata = {
  title: $('meta[property="og:title"]').attr('content')
    ?? $('title').text().trim(),
  description: $('meta[name="description"]').attr('content') ?? '',
  canonical: $('link[rel="canonical"]').attr('href') ?? null,
  image: $('meta[property="og:image"]').attr('content') ?? null,
};

const headings = $('h2')
  .map((_, el) => $(el).text().trim())
  .get()
  .filter((t) => t.length > 0)
  .slice(0, 5);

const wordCount = $('article')
  .text()
  .replace(/\s+/g, ' ')
  .trim()
  .split(' ')
  .filter(Boolean).length;

console.log(JSON.stringify(metadata, null, 2), headings, wordCount);