How do I get links in Cheerio?

You can get links in Cheerio by using the relevant selector expression and then using the .attr() method to extract the href from the nodes.

Here is some sample code that extracts all the anchor tags from the ScrapingBee homepage and then prints the text and href from the tags in the console:

const cheerio = require('cheerio');

fetch('https://scrapingbee.com')
    .then(function (response) {
        return response.text();
    })
    .then(function (html) {
        // Load the HTML in Cheerio
        const $ = cheerio.load(html);
        
        // Select all anchor tags from the page
        const links = $("a")

        // Loop over all the anchor tags
        links.each((index, value) => {
            // Print the text from the tags and the associated href
            console.log($(value).text(), " => ", $(value).attr("href"));
        })
    })
    .catch(function (err) {
        console.log('Failed to fetch page: ', err);
    });

Related Cheerio web scraping questions: