📜  Cheerio - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:57.996000             🧑  作者: Mango

Cheerio - JavaScript

Cheerio is a fast, flexible, and lean implementation of core jQuery for the server-side. It provides an easy-to-use API for parsing and manipulating HTML and XML documents. Cheerio can be used with a variety of web scraping and data extraction tasks.

Installation

To install Cheerio, you can use npm:

npm install cheerio
Usage

Using Cheerio is similar to using jQuery on the client-side. You start by loading an HTML or XML document and then selecting the elements you want to manipulate. Here's an example:

const cheerio = require('cheerio');
const $ = cheerio.load('<html><body><h1>Hello World</h1></body></html>');

$('h1').text('Hello Cheerio!');
console.log($.html());

In this example, we're loading an HTML document and then changing the text of the h1 element to "Hello Cheerio!". We then print the modified document to the console.

API

Cheerio provides a powerful API for selecting and manipulating HTML and XML documents. Here are some of the most commonly used methods:

  • $('selector'): Select elements based on a CSS selector.
  • .html(): Get or set the HTML contents of the selected element(s).
  • .text(): Get or set the text contents of the selected element(s).
  • .attr(name, value): Get or set the attribute value of the selected element(s).
  • .addClass(class): Add a class to the selected element(s).
  • .removeClass(class): Remove a class from the selected element(s).
  • .each(callback): Iterate over the selected element(s) and call a function for each one.
Conclusion

Cheerio is a powerful and flexible tool for parsing and manipulating HTML and XML documents in Node.js. It provides a familiar API for those who are already familiar with jQuery, making it easy to get started. With its fast and efficient implementation, Cheerio is a great choice for web scraping and data extraction tasks.