Using CSS Selectors Cheerio
Topic Overview
Welcome! In this lesson, we're going to focus on using CSS selectors in Cheerio. CSS selectors are powerful tools that allow you to pinpoint and extract precise information from a web page. Not only will you learn about the role of CSS selectors in web scraping, but also how to use these selectors with Cheerio to scrape data effectively from a web page using the power of Node.js.
Introduction to CSS Selectors
First, let's understand what CSS selectors are. In web development, CSS selectors are used to select HTML elements based on their id, class, type, attribute, etc., and apply specific CSS styles to them. For example, in a website's code, you might see a CSS rule like this:
And the corresponding CSS:
This rule makes all the HTML elements with class product have blue text and a font size of 16 pixels. The way product is targeted by the CSS rule is through the use of a selector.
This idea is used in web scraping, where CSS selectors help you navigate the HTML structure of the web page and extract the information you need. They offer a flexible way to search across the HTML content and find the data you want.
You can use CSS selectors in Cheerio using the $() function.
Using CSS Selectors with Cheerio
Now that you understand the concept of CSS selectors, let's dive into how you can use them with Cheerio.
Cheerio's $() function allows us to use CSS selectors to grab elements from an HTML document. The $() function returns a Cheerio object containing all the elements that match the CSS selector.
Take a look at our solution code to see how $() is used in practice:
The output of this code will be:
This output demonstrates how the $() function successfully found all divs with the class product and extracted the text from the <p> tags within those divs.
We created a variable products, which contains all the divs with class product. Then, we loop through products and print out the text in each div.
Remember our CSS selector rule: .product targets all the elements with class product. These target elements are being collected by Cheerio's $() function.
Similarly, we can select elements based on their ID. For example, #special will select the element with ID special.
