cheerio get href text
Cheerio get href text
As a blogger, I often need to extract information from HTML pages to create content for my website. One common task is to get the text of a hyperlink, or anchor, element using Cheerio.
Using Cheerio to Get Href Text
Cheerio is a fast and flexible library for parsing HTML and XML documents. It provides a simple and intuitive API for navigating and manipulating the document tree. To get the text of an anchor element using Cheerio, you can use the text()
method.
const cheerio = require('cheerio');
const html = '<div><a href="https://www.example.com">Example</a></div>';
const $ = cheerio.load(html);
const text = $('a').text();
console.log(text); // Output: Example
In this example, we first load an HTML string into Cheerio using the load()
method. We then find the anchor element using the selector 'a'
and call the text()
method to get its text content.
Using Cheerio to Get Href Attribute
Sometimes, we may also need to get the value of the href attribute of an anchor element. We can use the attr()
method for this purpose.
const cheerio = require('cheerio');
const html = '<div><a href="https://www.example.com">Example</a></div>';
const $ = cheerio.load(html);
const href = $('a').attr('href');
console.log(href); // Output: https://www.example.com
In this example, we again load the HTML string into Cheerio and find the anchor element using the selector 'a'
. We then call the attr()
method with the argument 'href'
to get the value of the href attribute.
Conclusion
Cheerio is a powerful tool for parsing and manipulating HTML and XML documents. With its simple and intuitive API, we can easily extract information from web pages and use it to create engaging content.