DE EN ES FR ID JA KO PT RU TH VI ZH

Referencia de la API de Cheerio

Cheerio es una implementación del lado del servidor rápida, flexible y elegante de la funcionalidad principal de jQuery. Proporciona una API familiar similar a jQuery para analizar y manipular documentos HTML y XML en entornos Node.js.

Funciones de Carga Principales

cheerio.load(content, options?)

Carga contenido HTML/XML y devuelve una instancia CheerioAPI para consulta y manipulación.

Signatura:

function load(
  content: string | AnyNode | AnyNode[] | Buffer,
  options?: CheerioOptions,
  isDocument?: boolean
): CheerioAPI

Parámetros:

Nombre Tipo Por Defecto Descripción
content string | AnyNode | AnyNode[] | Buffer - Contenido HTML/XML a analizar
options CheerioOptions {} Opciones del analizador y comportamiento
isDocument boolean true Si tratar el contenido como un documento completo

Devuelve: CheerioAPI - Una instancia de Cheerio con métodos similares a jQuery

Ejemplos:

import * as cheerio from 'cheerio';

// Basic HTML loading
const $ = cheerio.load('<ul><li>Apple</li><li>Orange</li></ul>');

// With options
const $ = cheerio.load('<xml><item>data</item></xml>', {
  xmlMode: true,
  decodeEntities: false
});

// Loading from buffer
const buffer = Buffer.from('<div>Hello</div>');
const $ = cheerio.load(buffer);

Errores comunes:

Selección de Elementos

$(selector, context?, root?)

Selecciona elementos del documento cargado usando selectores CSS, similar a la función $() de jQuery.

Signatura:

function $(
  selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
  context?: string | AnyNode | Cheerio<AnyNode>,
  root?: string | Document
): Cheerio<Element>

Parámetros:

Nombre Tipo Por Defecto Descripción
selector string | AnyNode | AnyNode[] | Cheerio<AnyNode> - Selector CSS o elementos a seleccionar
context string | AnyNode | Cheerio<AnyNode> document Contexto dentro del cual buscar
root string | Document - Documento raíz para el contexto

Devuelve: Cheerio<Element> - Colección de elementos coincidentes

Ejemplos:

// Basic selection
$('li').length; // Number of <li> elements
$('.apple').text(); // Text content of first element with class 'apple'

// With context
$('li', '#fruits').addClass('fruit'); // Find <li> within #fruits

// Complex selectors
$('li:nth-child(2n)').css('color', 'red'); // Every other <li>
$('a[href^="https://"]').attr('target', '_blank'); // External links

Manipulación de Atributos

.attr(name, value?)

Obtiene o establece atributos en los elementos coincidentes.

Signatura:

// Get attribute
function attr(name: string): string | undefined;
// Set attribute
function attr(name: string, value: string | null | ((i: number, attr: string) => string | null)): Cheerio<T>;
// Set multiple attributes
function attr(attributes: Record<string, string | null>): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
name string | Record<string, string | null> - Nombre del atributo o mapa de objeto
value string | null | function - Valor a establecer, null para eliminar, o función

Devuelve: string \| undefined \| Cheerio<T> - Valor del atributo (getter) o instancia Cheerio (setter)

Ejemplos:

// Get attribute
const href = $('a').attr('href'); // Gets href of first <a>

// Set attribute
$('img').attr('alt', 'Description'); // Sets alt text
$('a').attr('href', null); // Removes href attribute

// Multiple attributes
$('input').attr({
  type: 'text',
  placeholder: 'Enter name',
  required: 'required'
});

// Function-based setting
$('img').attr('src', (i, src) => src.replace('http://', 'https://'));

Errores comunes:

.prop(name, value?)

Obtiene o establece propiedades en elementos DOM, manejando propiedades especiales como checked, selected, etc.

Signatura:

// Get property
function prop(name: string): any;
// Set property
function prop(name: string, value: any): Cheerio<T>;
// Set multiple properties
function prop(properties: Record<string, any>): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
name string | Record<string, any> - Nombre de la propiedad o mapa de objeto
value any - Valor a establecer

Devuelve: any \| Cheerio<T> - Valor de la propiedad (getter) o instancia Cheerio (setter)

Ejemplos:

// Get property
const isChecked = $('input[type="checkbox"]').prop('checked'); // true/false

// Set property
$('input[type="checkbox"]').prop('checked', true);
$('option').prop('selected', false);

// Special properties
$('a').prop('href'); // Resolved absolute URL
$('div').prop('outerHTML'); // Full HTML including the element
$('div').prop('innerHTML'); // Inner HTML content

.data(key, value?)

Obtiene o establece atributos de datos con conversión automática de tipo para atributos HTML5 data-*.

Signatura:

// Get all data
function data(): Record<string, unknown>;
// Get specific data
function data(key: string): unknown;
// Set data
function data(key: string, value: unknown): Cheerio<T>;
// Set multiple data
function data(values: Record<string, unknown>): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
key string | Record<string, unknown> - Clave de datos o mapa de objeto
value unknown - Valor a establecer

Devuelve: unknown \| Record<string, unknown> \| Cheerio<T> - Valor de datos o instancia Cheerio

Ejemplos:

// HTML: <div data-user-id="123" data-active="true">
const userId = $('.user').data('userId'); // 123 (number)
const isActive = $('.user').data('active'); // true (boolean)

// Set data
$('.user').data('lastSeen', new Date());
$('.user').data({
  role: 'admin',
  permissions: ['read', 'write']
});

// Camel case conversion
$('<div data-foo-bar="test">').data('fooBar'); // "test"

Errores comunes:

Manipulación de Contenido

.text(value?)

Obtiene o establece el contenido de texto de los elementos, eliminando todas las etiquetas HTML.

Signatura:

// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
value string | number | function - Contenido de texto a establecer o función

Devuelve: string \| Cheerio<T> - Contenido de texto (getter) o instancia Cheerio (setter)

Ejemplos:

// Get text content
const title = $('h1').text(); // "Welcome to My Site"

// Set text (HTML-safe)
$('h1').text('New <Title>'); // Displays: "New <Title>" (not rendered as HTML)

// Function-based setting
$('li').text((i, currentText) => `${i + 1}. ${currentText}`);

.html(value?)

Obtiene o establece el contenido HTML interno de los elementos.

Signatura:

// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
value string | function - Contenido HTML a establecer o función

Devuelve: string \| null \| Cheerio<T> - Contenido HTML (getter) o instancia Cheerio (setter)

Ejemplos:

// Get HTML
const content = $('.container').html(); // "<p>Hello <strong>world</strong></p>"

// Set HTML
$('.container').html('<p>New content</p>');

// Function-based setting
$('div').html((i, oldHtml) => `<span>Item ${i}</span>${oldHtml}`);

Errores comunes:

.val(value?)

Obtiene o establece el valor de elementos de formulario (input, select, textarea).

Signatura:

// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
value string | string[] - Valor a establecer (array para multi-selección)

Devuelve: string \| string[] \| undefined \| Cheerio<T> - Valor del formulario o instancia Cheerio

Ejemplos:

// Get values
const inputValue = $('input[name="email"]').val(); // "user@example.com"
const selectedOptions = $('select[multiple]').val(); // ["option1", "option2"]

// Set values
$('input[type="text"]').val('New value');
$('select[multiple]').val(['option1', 'option3']); // Selects multiple options
$('textarea').val('Long text content...');

Manipulación del DOM

.append(content)

Inserta contenido como el último hijo de cada elemento coincidente.

Signatura:

function append(
  ...contents: (
    | string
    | AnyNode
    | AnyNode[]
    | Cheerio<AnyNode>
    | ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
  )[]
): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
contents string | AnyNode | Cheerio | function - Contenido a agregar

Devuelve: Cheerio<T> - La instancia Cheerio original

Ejemplos:

// Append HTML string
$('ul').append('<li>New item</li>');

// Append multiple items
$('ul').append('<li>Item 1</li>', '<li>Item 2</li>');

// Append Cheerio object
const $newLi = $('<li>').text('Dynamic item');
$('ul').append($newLi);

// Function-based appending
$('div').append((i, html) => `<p>Section ${i + 1}</p>`);

.remove(selector?)

Elimina elementos coincidentes del DOM.

Signatura:

function remove(selector?: string): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
selector string - Selector opcional para filtrar la eliminación

Devuelve: Cheerio<T> - Los elementos eliminados

Ejemplos:

// Remove all matched elements
$('.obsolete').remove();

// Remove with filtering
$('li').remove(':contains("delete")'); // Remove <li> containing "delete"

// Chain after removal
$('p').remove().appendTo('.archive'); // Move to archive

CSS y Estilos

.css(property, value?)

Obtiene o establece estilos CSS en elementos.

Signatura:

// Get style
function css(property: string): string | undefined;
// Set style
function css(property: string, value: string | ((i: number, style: string) => string)): Cheerio<T>;
// Set multiple styles
function css(properties: Record<string, string>): Cheerio<T>;
// Get multiple styles
function css(properties: string[]): Record<string, string>;

Parámetros:

Nombre Tipo Por Defecto Descripción
property string | string[] | Record<string, string> - Nombre de propiedad CSS, array u objeto
value string | function - Valor CSS a establecer o función

Devuelve: string \| Record<string, string> \| Cheerio<T> - Valor(es) CSS o instancia Cheerio

Ejemplos:

// Get computed style
const color = $('.highlight').css('color'); // "red"

// Set single style
$('.box').css('background-color', 'blue');

// Set multiple styles
$('.card').css({
  'border-radius': '8px',
  'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
  padding: '16px'
});

// Function-based setting
$('div').css('width', (i, width) => `${parseInt(width) + 10}px`);

.addClass(className)

Agrega clase(s) CSS a elementos coincidentes.

Signatura:

function addClass(
  className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
className string | function - Nombres de clase separados por espacios o función

Devuelve: Cheerio<T> - La instancia Cheerio para encadenamiento

Ejemplos:

// Add single class
$('.item').addClass('active');

// Add multiple classes
$('.card').addClass('highlighted featured');

// Function-based adding
$('li').addClass((i, currentClass) => {
  return i % 2 === 0 ? 'even' : 'odd';
});

.removeClass(className?)

Elimina clase(s) CSS de elementos coincidentes.

Signatura:

function removeClass(
  className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
className string | function - Clases a eliminar, o función (omitir para eliminar todas)

Devuelve: Cheerio<T> - La instancia Cheerio para encadenamiento

Ejemplos:

// Remove specific class
$('.item').removeClass('active');

// Remove multiple classes
$('.card').removeClass('highlighted featured');

// Remove all classes
$('.temp').removeClass();

// Function-based removal
$('div').removeClass((i, currentClass) => {
  return currentClass.includes('temp-') ? currentClass : '';
});

.hasClass(className)

Verifica si algún elemento coincidente tiene la clase CSS especificada.

Signatura:

function hasClass(className: string): boolean;

Parámetros:

Nombre Tipo Por Defecto Descripción
className string - Nombre de clase a verificar

Devuelve: boolean - Verdadero si algún elemento tiene la clase

Ejemplos:

// Check for class
if ($('.nav-item').hasClass('active')) {
  console.log('Found active navigation item');
}

// Conditional logic
$('.button').each(function() {
  if ($(this).hasClass('primary')) {
    $(this).css('font-weight', 'bold');
  }
});

Navegación y Filtrado

.find(selector)

Busca elementos descendientes que coincidan con el selector.

Signatura:

function find<T extends AnyNode>(selector: string): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
selector string - Selector CSS a buscar

Devuelve: Cheerio<T> - Colección de elementos descendientes encontrados

Ejemplos:

// Find descendants
const links = $('.nav').find('a'); // All <a> tags inside .nav

// Complex selectors
const activeLinks = $('.menu').find('li.active a[href]');

// Chain with other methods
$('.article').find('img').attr('loading', 'lazy');

.each(callback)

Itera sobre elementos coincidentes, ejecutando un callback para cada uno.

Signatura:

function each(
  callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;

Parámetros:

Nombre Tipo Por Defecto Descripción
callback function - Función a ejecutar para cada elemento

Devuelve: Cheerio<T> - La instancia Cheerio original

Ejemplos:

// Basic iteration
$('li').each(function(i, el) {
  console.log(`Item ${i}: ${$(el).text()}`);
});

// Early termination
$('.item').each(function(i) {
  if ($(this).hasClass('stop')) return false; // Break loop
  $(this).addClass(`item-${i}`);
});

// Arrow function (note: `this` context differs)
$('img').each((i, img) => {
  $(img).attr('alt', `Image ${i + 1}`);
});

Errores comunes:

Manejo de Formularios

.serialize()

Serializa elementos de formulario en una cadena de consulta codificada en URL.

Signatura:

function serialize(): string;

Devuelve: string - Datos del formulario codificados en URL

Ejemplos:

// Serialize entire form
const formData = $('form').serialize();
// "name=John&email=john%40example.com&subscribe=on"

// Serialize specific inputs
const inputData = $('input[type="text"], select').serialize();

.serializeArray()

Serializa elementos de formulario en un array de objetos nombre-valor.

Signatura:

function serializeArray(): Array<{ name: string; value: string }>;

Devuelve: Array<{ name: string; value: string }> - Array de objetos de datos del formulario

Ejemplos:

// Get structured form data
const formArray = $('form').serializeArray();
// [{ name: 'email', value: 'user@example.com' }, { name: 'subscribe', value: 'on' }]

// Convert to object
const formObject = {};
$('form').serializeArray().forEach(item => {
  formObject[item.name] = item.value;
});

Errores comunes: