Cheerio

Fast, flexible, and lean implementation of core jQuery designed specificall...

README

cheerio

Fast, flexible & lean implementation of core jQuery designed specifically for the server.
Build Status Coverage OpenCollective backers OpenCollective sponsors


  1. ```js
  2. const cheerio = require('cheerio');
  3. const $ = cheerio.load('<h2 class="title">Hello world</h2>');

  4. $('h2.title').text('Hello there!');
  5. $('h2').addClass('welcome');

  6. $.html();
  7. //=>

    Hello there!

  8. ```

Note


We are currently working on the 1.0.0 release of cheerio on the main branch. The source code for the last published version, 0.22.0, can be found here.

Installation


npm install cheerio

Features


❤ Familiar syntax:
Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.

ϟ Blazingly fast:
Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient.

❁ Incredibly flexible:
Cheerio wraps around parse5 parser and can optionally use @FB55's forgiving htmlparser2. Cheerio can parse nearly any HTML or XML document.

Cheerio is not a web browser


Cheerio parses markup and provides an API for traversing/manipulating the resulting data structure. It does not interpret the result as a web browser does. Specifically, it does _not_ produce a visual rendering, apply CSS, load external resources, or execute JavaScript which is common for a SPA (single page application). This makes Cheerio much, much faster than other solutions. If your use case requires any of this functionality, you should consider browser automation software like Puppeteer and Playwright or DOM emulation projects like JSDom.

API


Markup example we'll be using:


  1. ```html
  2. <ul id="fruits">
  3.   <li class="apple">Apple</li>
  4.   <li class="orange">Orange</li>
  5.   <li class="pear">Pear</li>
  6. </ul>
  7. ```

This is the HTML markup we will be using in all of the API examples.

Loading


First you need to load in the HTML. This step in jQuery is implicit, since jQuery operates on the one, baked-in DOM. With Cheerio, we need to pass in the HTML document.

This is the _preferred_ method:

  1. ```js
  2. // ES6 or TypeScript:
  3. import * as cheerio from 'cheerio';

  4. // In other environments:
  5. const cheerio = require('cheerio');

  6. const $ = cheerio.load('<ul id="fruits">...</ul>');

  7. $.html();
  8. //=>
      ...
  9. ```

Similar to web browser contexts, `load` will introduce ``, ``, and `` elements if they are not already present. You can set `load`'s third argument to `false` to disable this.

  1. ```js
  2. const $ = cheerio.load('<ul id="fruits">...</ul>', null, false);

  3. $.html();
  4. //=> '
      ...
    '
  5. ```

Optionally, you can also load in the HTML by passing the string as the context:

  1. ```js
  2. $('ul', '<ul id="fruits">...</ul>');
  3. ```

Or as the root:

  1. ```js
  2. $('li', 'ul', '<ul id="fruits">...</ul>');
  3. ```

If you need to modify parsing options for XML input, you may pass an extra
object to .load():

  1. ```js
  2. const $ = cheerio.load('<ul id="fruits">...</ul>', {
  3.   xml: {
  4.     xmlMode: true,
  5.     withStartIndices: true,
  6.   },
  7. });
  8. ```

The options in the xml object are taken directly from htmlparser2, therefore any options that can be used inhtmlparser2 are valid in cheerio as well. When xml is set, the default options are:

  1. ```js
  2. {
  3.     xmlMode: true,
  4.     decodeEntities: true, // Decode HTML entities.
  5.     withStartIndices: false, // Add a `startIndex` property to nodes.
  6.     withEndIndices: false, // Add an `endIndex` property to nodes.
  7. }
  8. ```

For a full list of options and their effects, see domhandler and

Using htmlparser2


Cheerio ships with two parsers, parse5 and htmlparser2. The
former is the default for HTML, the latter the default for XML.

Some users may wish to parse markup with the htmlparser2 library, and
traverse/manipulate the resulting structure with Cheerio. This may be the case
for those upgrading from pre-1.0 releases of Cheerio (which relied on
htmlparser2), for those dealing with invalid markup (because htmlparser2 is
more forgiving), or for those operating in performance-critical situations
(because htmlparser2 may be faster in some cases). Note that "more forgiving"
means htmlparser2 has error-correcting mechanisms that aren't always a match
for the standards observed by web browsers. This behavior may be useful when
parsing non-HTML content.

To support these cases, load also accepts a htmlparser2-compatible data
structure as its first argument. Users may install htmlparser2, use it to
parse input, and pass the result to load:

  1. ```js
  2. // Usage as of htmlparser2 version 6:
  3. const htmlparser2 = require('htmlparser2');
  4. const dom = htmlparser2.parseDocument(document, options);

  5. const $ = cheerio.load(dom);
  6. ```

If you want to save some bytes, you can use Cheerio's _slim_ export, which
always uses htmlparser2:

  1. ```js
  2. const cheerio = require('cheerio/lib/slim');
  3. ```

Selectors


Cheerio's selector implementation is nearly identical to jQuery's, so the API is very similar.

\$( selector, [context], [root] )


selector searches within the context scope which searches within the root scope. selector and context can be a string expression, DOM Element, array of DOM elements, or cheerio object. root is typically the HTML document string.

This selector method is the starting point for traversing and manipulating the document. Like jQuery, it's the primary method for selecting elements in the document.

  1. ```js
  2. $('.apple', '#fruits').text();
  3. //=> Apple

  4. $('ul .pear').attr('class');
  5. //=> pear

  6. $('li[class=orange]').html();
  7. //=> Orange
  8. ```

XML Namespaces

You can select with XML Namespaces but due to the CSS specification, the colon (:) needs to be escaped for the selector to be valid.

  1. ```js
  2. $('[xml\\:id="main"');
  3. ```

Rendering


When you're ready to render the document, you can call the html method on the "root" selection:

  1. ```js
  2. $.root().html();
  3. //=>  
  4. //      
  5. //      
  6. //        
    • //          
    • Apple
    • //          
    • Orange
    • //          
    • Pear
    • //        
  7. //      
  8. //    
  9. ```

If you want to render the [outerHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) of a selection, you can use the html utility functon:

  1. ```js
  2. cheerio.html($('.pear'));
  3. //=>
  4. Pear
  5. ```

You may also render the text content of a Cheerio object using the text static method:

  1. ```js
  2. const $ = cheerio.load('This is <em>content</em>.');
  3. cheerio.text($('body'));
  4. //=> This is content.
  5. ```

Plugins


Once you have loaded a document, you may extend the prototype or the equivalent fn property with custom plugin methods:

  1. ```js
  2. const $ = cheerio.load('<html><body>Hello, <b>world</b>!</body></html>');
  3. $.prototype.logHtml = function () {
  4.   console.log(this.html());
  5. };

  6. $('body').logHtml(); // logs "Hello, world!" to the console
  7. ```

If you're using TypeScript, you should add a type definition for your new method:

  1. ```ts
  2. declare module 'cheerio' {
  3.   interface Cheerio<T> {
  4.     logHtml(this: Cheerio<T>): void;
  5.   }
  6. }
  7. ```

The "DOM Node" object


Cheerio collections are made up of objects that bear some resemblance to browser-based DOM nodes. You can expect them to define the following properties:

- tagName
- parentNode
- previousSibling
- nextSibling
- nodeValue
- firstChild
- childNodes
- lastChild

Screencasts



This video tutorial is a follow-up to Nettut's "How to Scrape Web Pages with Node.js and jQuery", using cheerio instead of JSDOM + jQuery. This video shows how easy it is to use cheerio and how much faster cheerio is than JSDOM + jQuery.


Cheerio in the real world


Are you using cheerio in production? Add it to the wiki!

Sponsors


Does your company use Cheerio in production? Please consider sponsoring this project! Your help will allow maintainers to dedicate more time and resources to its development and support.

CryptoCasinosCasinoonlineaams.comApifyFree BetsCasino utan svensk licensCasino utan svensk licensCasino utan svensk licensZenRowsScommessesportivemania.comNettikasinot.orgCasinosicuri.info

Backers


Become a backer to show your support for Cheerio and help us maintain and improve this open source project.

AirbnbVasy KafidoffEspen KlemJarrod DavisGautham ChandraCharles Severancenull

Special Thanks


This library stands on the shoulders of some incredible developers. A special thanks to:

• @FB55 for node-htmlparser2 & CSSSelect:
Felix has a knack for writing speedy parsing engines. He completely re-wrote both @tautologistic's node-htmlparser and @harry's node-soupselect from the ground up, making both of them much faster and more flexible. Cheerio would not be possible without his foundational work

• @jQuery team for jQuery:
The core API is the best of its class and despite dealing with all the browser inconsistencies the code base is extremely clean and easy to follow. Much of cheerio's implementation and documentation is from jQuery. Thanks guys.

• @visionmedia:
The style, the structure, the open-source"-ness" of this library comes from studying TJ's style and using many of his libraries. This dude consistently pumps out high-quality libraries and has always been more than willing to help or answer questions. You rock TJ.

License


MIT