Referência da API do Cheerio
Cheerio é uma implementação rápida, flexível e elegante da funcionalidade principal do jQuery para o lado servidor. Fornece uma API familiar similar ao jQuery para análise e manipulação de documentos HTML e XML em ambientes Node.js.
Funções de Carregamento Principais
cheerio.load(content, options?)
Carrega conteúdo HTML/XML e retorna uma instância CheerioAPI para consulta e manipulação.
Assinatura:
function load(
content: string | AnyNode | AnyNode[] | Buffer,
options?: CheerioOptions,
isDocument?: boolean
): CheerioAPI
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
content |
string | AnyNode | AnyNode[] | Buffer |
- | Conteúdo HTML/XML para análise |
options |
CheerioOptions |
{} |
Opções do analisador e comportamento |
isDocument |
boolean |
true |
Se deve tratar o conteúdo como um documento completo |
Retorna: CheerioAPI - Uma instância Cheerio com métodos similares ao jQuery
Exemplos:
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);
Pegadinhas comuns:
- O modo XML deve ser explicitamente habilitado para documentos XML
- Por padrão, aplicam-se as regras do analisador HTML5 (tags de fechamento automático, etc.)
- A codificação do Buffer é automaticamente detectada, mas pode precisar de especificação explícita
Seleção de Elementos
$(selector, context?, root?)
Seleciona elementos do documento carregado usando seletores CSS, similar à função $() do jQuery.
Assinatura:
function $(
selector: string | AnyNode | AnyNode[] | Cheerio<AnyNode>,
context?: string | AnyNode | Cheerio<AnyNode>,
root?: string | Document
): Cheerio<Element>
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
selector |
string | AnyNode | AnyNode[] | Cheerio<AnyNode> |
- | Seletor CSS ou elementos para selecionar |
context |
string | AnyNode | Cheerio<AnyNode> |
document |
Contexto dentro do qual buscar |
root |
string | Document |
- | Documento raiz para o contexto |
Retorna: Cheerio<Element> - Coleção de elementos correspondentes
Exemplos:
// 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
Manipulação de Atributos
.attr(name, value?)
Obtém ou define atributos nos elementos correspondentes.
Assinatura:
// 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:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
name |
string | Record<string, string | null> |
- | Nome do atributo ou mapa de objetos |
value |
string | null | function |
- | Valor a definir, null para remover, ou função |
Retorna: string \| undefined \| Cheerio<T> - Valor do atributo (getter) ou instância Cheerio (setter)
Exemplos:
// 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://'));
Pegadinhas comuns:
- Definir atributo como
nullo remove completamente - Atributos booleanos retornam seu nome quando presentes (
'checked'), nãotrue - Funções recebem índice e valor atual como parâmetros
.prop(name, value?)
Obtém ou define propriedades em elementos DOM, lidando com propriedades especiais como checked, selected, etc.
Assinatura:
// 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:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
name |
string | Record<string, any> |
- | Nome da propriedade ou mapa de objetos |
value |
any |
- | Valor a definir |
Retorna: any \| Cheerio<T> - Valor da propriedade (getter) ou instância Cheerio (setter)
Exemplos:
// 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?)
Obtém ou define atributos de dados com conversão automática de tipo para atributos HTML5 data-*.
Assinatura:
// 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:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
key |
string | Record<string, unknown> |
- | Chave dos dados ou mapa de objetos |
value |
unknown |
- | Valor a definir |
Retorna: unknown \| Record<string, unknown> \| Cheerio<T> - Valor dos dados ou instância Cheerio
Exemplos:
// 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"
Pegadinhas comuns:
- Atributos de dados são automaticamente analisados (JSON, números, booleanos)
- Chaves em camelCase são mapeadas para atributos de dados com hífens
- Dados definidos via
.data()não atualizam o atributo HTML real
Manipulação de Conteúdo
.text(value?)
Obtém ou define o conteúdo de texto dos elementos, removendo todas as tags HTML.
Assinatura:
// Get text
function text(): string;
// Set text
function text(value: string | number | ((i: number, text: string) => string | number)): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
value |
string | number | function |
- | Conteúdo de texto a definir ou função |
Retorna: string \| Cheerio<T> - Conteúdo de texto (getter) ou instância Cheerio (setter)
Exemplos:
// 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?)
Obtém ou define o conteúdo HTML interno dos elementos.
Assinatura:
// Get HTML
function html(): string | null;
// Set HTML
function html(value: string | ((i: number, html: string) => string)): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
value |
string | function |
- | Conteúdo HTML a definir ou função |
Retorna: string \| null \| Cheerio<T> - Conteúdo HTML (getter) ou instância Cheerio (setter)
Exemplos:
// 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}`);
Pegadinhas comuns:
.html()retorna HTML interno, use.prop('outerHTML')para o elemento completo- Definir HTML sobrescreve todo o conteúdo existente
- HTML não é sanitizado - tenha cuidado com entrada do usuário
.val(value?)
Obtém ou define o valor de elementos de formulário (input, select, textarea).
Assinatura:
// Get value
function val(): string | string[] | undefined;
// Set value
function val(value: string | string[]): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
value |
string | string[] |
- | Valor a definir (array para multi-seleção) |
Retorna: string \| string[] \| undefined \| Cheerio<T> - Valor do formulário ou instância Cheerio
Exemplos:
// 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...');
Manipulação do DOM
.append(content)
Insere conteúdo como último filho de cada elemento correspondente.
Assinatura:
function append(
...contents: (
| string
| AnyNode
| AnyNode[]
| Cheerio<AnyNode>
| ((i: number, html: string) => string | AnyNode | Cheerio<AnyNode>)
)[]
): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
contents |
string | AnyNode | Cheerio | function |
- | Conteúdo a anexar |
Retorna: Cheerio<T> - A instância Cheerio original
Exemplos:
// 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?)
Remove elementos correspondentes do DOM.
Assinatura:
function remove(selector?: string): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
selector |
string |
- | Seletor opcional para filtrar a remoção |
Retorna: Cheerio<T> - Os elementos removidos
Exemplos:
// 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 e Estilização
.css(property, value?)
Obtém ou define estilos CSS em elementos.
Assinatura:
// 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:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
property |
string | string[] | Record<string, string> |
- | Nome da propriedade CSS, array ou objeto |
value |
string | function |
- | Valor CSS a definir ou função |
Retorna: string \| Record<string, string> \| Cheerio<T> - Valor(es) CSS ou instância Cheerio
Exemplos:
// 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)
Adiciona classe(s) CSS aos elementos correspondentes.
Assinatura:
function addClass(
className: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
className |
string | function |
- | Nomes de classes separados por espaço ou função |
Retorna: Cheerio<T> - A instância Cheerio para encadeamento
Exemplos:
// 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?)
Remove classe(s) CSS dos elementos correspondentes.
Assinatura:
function removeClass(
className?: string | ((i: number, currentClass: string) => string)
): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
className |
string | function |
- | Classes a remover, ou função (omitir para remover todas) |
Retorna: Cheerio<T> - A instância Cheerio para encadeamento
Exemplos:
// 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 se algum elemento correspondente possui a classe CSS especificada.
Assinatura:
function hasClass(className: string): boolean;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
className |
string |
- | Nome da classe a verificar |
Retorna: boolean - True se algum elemento possui a classe
Exemplos:
// 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');
}
});
Navegação e Filtragem
.find(selector)
Busca por elementos descendentes que correspondem ao seletor.
Assinatura:
function find<T extends AnyNode>(selector: string): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
selector |
string |
- | Seletor CSS a buscar |
Retorna: Cheerio<T> - Coleção de elementos descendentes encontrados
Exemplos:
// 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 correspondentes, executando um callback para cada um.
Assinatura:
function each(
callback: (this: T, i: number, el: T) => void | false
): Cheerio<T>;
Parâmetros:
| Nome | Tipo | Padrão | Descrição |
|---|---|---|---|
callback |
function |
- | Função a executar para cada elemento |
Retorna: Cheerio<T> - A instância Cheerio original
Exemplos:
// 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}`);
});
Pegadinhas comuns:
- Retorne
falsedo callback para interromper o loop antecipadamente - Arrow functions não vinculam
thisao elemento atual - O parâmetro de índice é baseado em zero
Manipulação de Formulários
.serialize()
Serializa elementos de formulário em uma string de consulta codificada em URL.
Assinatura:
function serialize(): string;
Retorna: string - Dados do formulário codificados em URL
Exemplos:
// 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 formulário em um array de objetos nome-valor.
Assinatura:
function serializeArray(): Array<{ name: string; value: string }>;
Retorna: Array<{ name: string; value: string }> - Array de objetos de dados do formulário
Exemplos:
// 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;
});
Pegadinhas comuns:
- Apenas controles de formulário bem-sucedidos são serializados
- Elementos desabilitados são ignorados
- Checkboxes/radios devem estar marcados para serem incluídos
- Inputs de arquivo retornam o nome do arquivo, não o conteúdo do arquivo