jQuery in Node.js with Cheerio

Advertisement

Advertisement

jQuery provide a convenient way to access elements using CSS selectors. Node.js has a package called Cheerio that allows us to make jQuery style code. The Request module can be used in tandem to provide the ability to perform an HTTP GET to fetch remote HTML documents. That is useful for web scraping.

Be sure to install the Cheerio and Request packages before you start.

Installing NPM Packages

Add the -g flag to install globally instead of in the current directory

npm install cheerio request

Using jQuery Style Selectors

var request = require('request');
var cheerio = require('cheerio');

request('http://devdungeon.com/archive', function(err, resp, body) {
if (err) throw err;

    // Load string containing the HTML document
// $ can be used just like jQuery
$ = cheerio.load(body);

// List the titles of all posts in my blog archive
$('.view-blog-archive a').each(function() {
    console.log($(this).text());
});

});

Advertisement

Advertisement