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

javascriptsnippet
29 lines
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);

How the snippet works

Every asynchronous step is awaited, so rejections surface where the call happens.

The whole file runs on the top-level bindings declared above: html, metadata, headings, wordCount.

Watch out for

  • Plan for an install step: cheerio is a real dependency, resolved by the package manager.
  • A browser is the runtime here: fetch are not available in Node.

Statements that matter

.then((r) => r.text());
.map((_, el) => $(el).text().trim())
.get()
.filter((t) => t.length > 0)
.slice(0, 5);

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `cheerio`. Add it to your project before running the snippet.