To install Cheerio in a Node.js project, you will need to use npm (Node Package Manager), which comes bundled with Node.js. Cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server.
Here is how you can install Cheerio in your Node.js project:
- Open a terminal or command prompt.
If you’re using an Integrated Development Environment (IDE) like Visual Studio Code, you can open the built-in terminal.
- Navigate to your project directory.
Use the cd
command to change directories to your Node.js project where you want to install Cheerio.
cd path/to/your/project
- Run the npm install command.
In your terminal, run the following command to install Cheerio:
npm install cheerio
This will install the latest version of Cheerio and add it to your project's package.json
file under the dependencies section. If you want to save it as a development dependency (useful for scenarios where Cheerio is only needed during development, such as writing tests), you can use the --save-dev
flag:
npm install cheerio --save-dev
- Verify the installation.
After running the command, you can verify that Cheerio has been installed by checking your package.json
file or by looking for the cheerio
folder within the node_modules
directory of your project.
Here is a simple example of using Cheerio to scrape data from an HTML string in a Node.js script:
const cheerio = require('cheerio');
const html = `
<ul id="fruits">
<li class="apple">Apple</li>
<li class="orange">Orange</li>
<li class="pear">Pear</li>
</ul>
`;
// Load the HTML string into Cheerio
const $ = cheerio.load(html);
// Select the elements and output their text content
$('.apple', '#fruits').each(function () {
console.log($(this).text()); // Output: Apple
});
Remember that Cheerio is a parsing library and doesn't handle HTTP requests. If you need to scrape content from live websites, you'll also need a library like axios
or node-fetch
to perform the HTTP requests to get the HTML content. Then you can pass the HTML response to Cheerio for parsing and manipulation.