Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

cheerio

БесплатноБез исполняемых скриптовНе проверен

Parse and extract data from HTML with Cheerio. Use when a user asks to scrape static web pages, parse HTML files, extract data from HTML, build a web scraper…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Cheerio

Overview

Cheerio is a fast, lightweight HTML/XML parser for Node.js that implements a jQuery-like API. Unlike Puppeteer, it does not run a browser — it parses raw HTML strings, so it is far lighter than a headless browser and ideal for scraping server-rendered pages, parsing HTML files, and transforming HTML content. Pair it with fetch or axios for web scraping, or use it standalone for HTML processing.

Instructions

Step 1: Installation

npm install cheerio

Cheerio 1.x is ESM-first and needs Node 20.18.1 or later. Use import * as cheerio from 'cheerio' (there is no default export); CommonJS can still require('cheerio').

Step 2: Parse HTML and Extract Data

// parse_html.js — Load HTML and extract structured data with CSS selectors
import * as cheerio from 'cheerio'

const html = `
<html>
  <body>
    <h1>Products</h1>
    <div class="product" data-id="1">
      <h2>Widget Pro</h2>
      <span class="price">$29.99</span>
      <a href="/products/widget-pro">Details</a>
    </div>
    <div class="product" data-id="2">
      <h2>Gadget Max</h2>
      <span class="price">$49.99</span>
      <a href="/products/gadget-max">Details</a>
    </div>
  </body>
</html>`

const $ = cheerio.load(html)

// Extract all products: .map() returns a Cheerio object, .get() turns it into an array
const products = $('.product').map((i, el) => ({
  id: $(el).attr('data-id'),
  title: $(el).find('h2').text().trim(),
  price: parseFloat($(el).find('.price').text().replace('$', '')),
  link: $(el).find('a').attr('href'),
})).get()

console.log(products)
// [{ id: '1', title: 'Widget Pro', price: 29.99, link: '/products/widget-pro' }, ...]

// Declarative alternative: .extract() maps selectors to fields in one call
const page = $.extract({
  titles: [{ selector: '.product h2' }],
  links: [{ selector: '.product a', value: 'href' }],
})
// { titles: ['Widget Pro', 'Gadget Max'], links: ['/products/widget-pro', '/products/gadget-max'] }

Step 3: Web Scraping with Fetch

// scrape_site.js — Fetch a page and extract data
import * as cheerio from 'cheerio'

async function scrape(url) {
  const response = await fetch(url, {
    headers: { 'user-agent': 'price-watch-bot (+https://shop-tools.dev/bot)' },
  })
  if (!response.ok) throw new Error(`${url} answered ${response.status}`)
  const html = await response.text()
  const $ = cheerio.load(html)

  // Extract all links
  const links = []
  $('a[href]').each((i, el) => {
    links.push({
      text: $(el).text().trim(),
      href: $(el).attr('href'),
    })
  })

  // Extract meta tags
  const meta = {
    title: $('title').text(),
    description: $('meta[name="description"]').attr('content'),
    ogImage: $('meta[property="og:image"]').attr('content'),
  }

  return { links, meta }
}

For a plain GET, await cheerio.fromURL(url) fetches and parses in one call. It needs requestOptions.method set if you pass requestOptions at all, so use fetch as above when you need custom headers. cheerio.load(html, { xml: true }) parses RSS and other XML (selectors like item title work).

Step 4: Advanced Selectors and Traversal

// selectors.js — Complex CSS selectors and DOM traversal
const $ = cheerio.load(html)

// Attribute selectors
$('a[href^="https"]')           // links starting with https
$('img[src$=".png"]')           // PNG images
$('div[class*="product"]')      // divs with "product" in class

// Traversal
$('.product').first()            // first product
$('.product').last()             // last product
$('.product').eq(2)              // third product (0-indexed)
$('.price').parent()             // parent of each .price element
$('.product').children('h2')     // direct h2 children
$('.product').find('.price')     // descendants matching .price
$('.product').next()             // next sibling
$('.product').prev()             // previous sibling
$('a').map((i, el) => $(el).attr('href')).get()  // array of values

// Filtering
$('.product').filter((i, el) => {
  const price = parseFloat($(el).find('.price').text().replace('$', ''))
  return price < 50
})

// Text and HTML
$('.product').first().text()     // all text content, flattened
$('.product').first().html()     // inner HTML

Step 5: Table Extraction

// extract_table.js — Parse HTML tables into structured data
function extractTable($, tableSelector) {
  /**
   * Convert an HTML table to an array of objects using headers as keys.
   * Args:
   *   $: Cheerio instance
   *   tableSelector: CSS selector for the table element
   */
  const headers = []
  $(`${tableSelector} thead th`).each((i, el) => {
    headers.push($(el).text().trim())
  })

  const rows = []
  $(`${tableSelector} tbody tr`).each((i, tr) => {
    const row = {}
    $(tr).find('td').each((j, td) => {
      row[headers[j]] = $(td).text().trim()
    })
    rows.push(row)
  })
  return rows
}

// Usage
const tableData = extractTable(
Полный SKILL.md на GitHub

Установить cheerio в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл cheerio?

Parse and extract data from HTML with Cheerio. Use when a user asks to scrape static web pages, parse HTML files, extract data from HTML, build a web scraper for server-rendered pages, extract text or links from HTML documents, parse RSS/XML feeds, transform HTML content, or process HTML emails. Covers jQuery-style selectors, DOM traversal, text extraction, attribute parsing, and integration with HTTP clients for web scraping pipelines.

Как установить скилл cheerio?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл cheerio запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить cheerio с