cheerio
Last updated
Last updated
Fast, flexible & lean implementation of core jQuery designed specifically for the server.
npm install cheerio
❤ 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. Preliminary end-to-end benchmarks suggest that cheerio is about 8x faster than JSDOM.
❁ Incredibly flexible: Cheerio wraps around @FB55's forgiving htmlparser2. Cheerio can parse nearly any HTML or XML document.
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.
Become a backer to show your support for Cheerio and help us maintain and improve this open source project.
This is the HTML markup we will be using in all of the API examples.
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:
Optionally, you can also load in the HTML by passing the string as the context:
Or as the root:
You can also pass an extra object to .load()
if you need to modify any of the default parsing options:
These parsing options are taken directly from htmlparser2, therefore any options that can be used in htmlparser2
are valid in cheerio as well. The default options are:
For a full list of options and their effects, see this and htmlparser2's options.
Cheerio's selector implementation is nearly identical to jQuery's, so the API is very similar.
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, but unlike jQuery it's built on top of the CSSSelect library, which implements most of the Sizzle selectors.
Methods for getting and modifying attributes.
Method for getting and setting attributes. Gets the attribute value for only the first element in the matched set. If you set an attribute's value to null
, you remove that attribute. You may also pass a map
and function
like jQuery.
See http://api.jquery.com/attr/ for more information
Method for getting and setting properties. Gets the property value for only the first element in the matched set.
See http://api.jquery.com/prop/ for more information
Method for getting and setting data attributes. Gets or sets the data attribute value for only the first element in the matched set.
See http://api.jquery.com/data/ for more information
Method for getting and setting the value of input, select, and textarea. Note: Support for map
, and function
has not been added yet.
Method for removing attributes by name
.
Check to see if any of the matched elements have the given className
.
Adds class(es) to all of the matched elements. Also accepts a function
like jQuery.
See http://api.jquery.com/addClass/ for more information.
Removes one or more space-separated classes from the selected elements. If no className
is defined, all classes will be removed. Also accepts a function
like jQuery.
See http://api.jquery.com/removeClass/ for more information.
Add or remove class(es) from the matched elements, depending on either the class's presence or the value of the switch argument. Also accepts a function
like jQuery.
See http://api.jquery.com/toggleClass/ for more information.
Checks the current list of elements and returns true
if any of the elements match the selector. If using an element or Cheerio selection, returns true
if any of the elements match. If using a predicate function, the function is executed in the context of the selected element, so this
refers to the current element.
Encode a set of form elements as an array of names and values.
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
Get a set of parents filtered by selector
of each element in the current set of match elements.
Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or cheerio object.
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
Gets the next sibling of the first selected element, optionally filtered by a selector.
Gets all the following siblings of the first selected element, optionally filtered by a selector.
Gets all the following siblings up to but not including the element matched by the selector, optionally filtered by another selector.
Gets the previous sibling of the first selected element optionally filtered by a selector.
Gets all the preceding siblings of the first selected element, optionally filtered by a selector.
Gets all the preceding siblings up to but not including the element matched by the selector, optionally filtered by another selector.
Gets the elements matching the specified range
Gets the first selected element's siblings, excluding itself.
Gets the children of the first selected element.
Gets the children of each element in the set of matched elements, including text and comment nodes.
Iterates over a cheerio object, executing a function for each matched element. When the callback is fired, the function is fired in the context of the DOM element, so this
refers to the current element, which is equivalent to the function parameter element
. To break out of the each
loop early, return with false
.
Pass each element in the current matched set through a function, producing a new Cheerio object containing the return values. The function can return an individual data item or an array of data items to be inserted into the resulting set. If an array is returned, the elements inside the array are inserted into the set. If the function returns null or undefined, no element will be inserted.
Iterates over a cheerio object, reducing the set of selector elements to those that match the selector or pass the function's test. When a Cheerio selection is specified, return only the elements contained in that selection. When an element is specified, return only that element (if it is contained in the original selection). If using the function method, the function is executed in the context of the selected element, so this
refers to the current element.
Selector:
Function:
Remove elements from the set of matched elements. Given a jQuery object that represents a set of DOM elements, the .not()
method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; the elements that don't match the selector will be included in the result. The .not()
method can take a function as its argument in the same way that .filter()
does. Elements for which the function returns true are excluded from the filtered set; all other elements are included.
Selector:
Function:
Filters the set of matched elements to only those which have the given DOM element as a descendant or which have a descendant that matches the given selector. Equivalent to .filter(':has(selector)')
.
Selector:
Element:
Will select the first element of a cheerio object
Will select the last element of a cheerio object
Reduce the set of matched elements to the one at the specified index. Use .eq(-i)
to count backwards from the last selected element.
Retrieve the DOM elements matched by the Cheerio object. If an index is specified, retrieve one of the elements matched by the Cheerio object:
If no index is specified, retrieve all elements matched by the Cheerio object:
Search for a given element from among the matched elements.
End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.
Add elements to the set of matched elements.
Add the previous set of elements on the stack to the current set, optionally filtered by a selector.
Methods for modifying the DOM structure.
Inserts content as the last child of each of the selected elements.
Insert every element in the set of matched elements to the end of the target.
Inserts content as the first child of each of the selected elements.
Insert every element in the set of matched elements to the beginning of the target.
Insert content next to each element in the set of matched elements.
Insert every element in the set of matched elements after the target.
Insert content previous to each element in the set of matched elements.
Insert every element in the set of matched elements before the target.
Removes the set of matched elements from the DOM and all their children. selector
filters the set of matched elements to be removed.
Replaces matched elements with content
.
Empties an element, removing all its children.
Gets an html content string from the first selected element. If htmlString
is specified, each selected element's content is replaced by the new content.
Get the combined text contents of each element in the set of matched elements, including their descendants.. If textString
is specified, each selected element's content is replaced by the new text content.
The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.
Get the value of a style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.
When you're ready to render the document, you can use the html
utility function:
If you want to return the outerHTML you can use $.html(selector)
:
By default, html
will leave some tags open. Sometimes you may instead want to render a valid XML document. For example, you might parse the following XML snippet:
... and later want to render to XML. To do this, you can use the 'xml' utility function:
You may also render the text content of a Cheerio object using the text
static method:
The method may be called on the Cheerio module itself--be sure to pass a collection of nodes!
DOM element methods that don't fit anywhere else
Retrieve all the DOM elements contained in the jQuery set as an array.
Clone the cheerio object.
Sometimes you need to work with the top-level root element. To query it, you can use $.root()
.
Checks to see if the contained
DOM element is a descendant of the container
DOM element.
Parses a string into an array of DOM nodes. The context
argument has no meaning for Cheerio, but it is maintained for API compatability.
Load in the HTML. (See the previous section titled "Loading" for more information.)
Once you have loaded a document, you may extend the prototype or the equivalent fn
property with custom plugin methods:
Cheerio collections are made up of objects that bear some resemblence to browser-based DOM nodes. You can expect them to define the following properties:
tagName
parentNode
previousSibling
nextSibling
nodeValue
firstChild
childNodes
lastChild
I wrote cheerio because I found myself increasingly frustrated with JSDOM. For me, there were three main sticking points that I kept running into again and again:
• JSDOM's built-in parser is too strict: JSDOM's bundled HTML parser cannot handle many popular sites out there today.
• JSDOM is too slow: Parsing big websites with JSDOM has a noticeable delay.
• JSDOM feels too heavy: The goal of JSDOM is to provide an identical DOM environment as what we see in the browser. I never really needed all this, I just wanted a simple, familiar way to do HTML manipulation.
Cheerio will not solve all your problems. I would still use JSDOM if I needed to work in a browser-like environment on the server, particularly if I wanted to automate functional tests.
http://vimeo.com/31950192
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.
These are some of the contributors that have made cheerio possible:
Are you using cheerio in production? Add it to the wiki!
To run the test suite, download the repository, then within the cheerio directory, run:
This will download the development packages and run the test suite.
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.
MIT