Extracting Text with Cheerio
Introducing Cheerio and jQuery-like Selectors
Hello and welcome! In this lesson, we're learning about extracting text from paragraphs using Cheerio. As you might recall from our previous lesson, Cheerio provides a server-side implementation of core jQuery functionality, allowing us to traverse and manipulate HTML documents using familiar CSS selectors.
In this lesson, we will often use Cheerio's $() function — a powerful tool that uses CSS selectors to find elements in a document and returns a Cheerio object, allowing us to extract text from specific HTML elements. Cheerio objects are jQuery-like collections that can be iterated over to access the content of the HTML elements. This approach is versatile, allowing us to filter HTML elements by their tag name, attributes, classes, IDs, or even by their position within the document using CSS selector syntax.
Extracting Paragraphs from HTML Content
Now, let's define a simple HTML content and extract text from paragraph tags using Cheerio. Here's a quick example:
Remember our $() function? You can use it with CSS selectors to locate all p tags in our loaded HTML:
To see the actual HTML elements, you can iterate through them:
The output of the above code will be:
This output demonstrates how Cheerio can easily locate all p tags within our HTML content using CSS selectors, returning them as a Cheerio object that we can work with. It's a foundational step for extracting data from specific HTML elements.
Want just the raw text, with no HTML tags? You can access the text of each element using the .text() method:
The output of the above code will be:
This illustrates how easily you can extract and directly work with the text content of HTML elements, stripping away the HTML markup to get to the raw information you're after.
And just like that, you've extracted text from the paragraph tags in your HTML!
