Ad

How To Crawl Javascript (vuejs, Reactjs) Web Site With Nodejs

- 1 answer

I was going to crawl vue js frontend web site when I try to crawl that it doesn't load the content to cheerio.. what i was getting , a blank web page. my code as follows

getSiteContentAsJs = (url) => {
  return new Promise((resolve, reject) => {
    let j = request.jar();
    request.get({url: url, jar: j}, function(err, response, body) {
        if(err)
          return resolve({body: null, jar: j, error: err});
        return resolve({body: body, jar: j, error: null});
    });
  })
}

I got my content as follows

const { body, jar, error} = await getSiteContentAsJs(url);
//I passed body to cheerio to get the js object out of the web content
const $ = cheerio.load(body);

but there is nothing rendered. but a blank web page. no content in it.

Ad

Answer

I found that cheerio doesn't run javascript. since this web site based on vue front end I needed a virtual browser which actually run js and render me the output

so instead of using request I used phantom to render js web pages

const phantom = require('phantom');
const cheerio = require('cheerio');

loadJsSite = async (url) => {
  const instance = await phantom.create();
  const page = await instance.createPage();
  await page.on('onResourceRequested', function(requestData) {
    console.info('Requesting', requestData.url);
  });

  const status = await page.open(url);
  const content = await page.property('content');
  // console.log(content);
  // let $ = cheerio.load(content);

  await instance.exit();

  return {$: cheerio.load(content), content: content};
} 

now I can get the rendered page like below

const {$, content} = await loadJsSite(url);
// I can query like this
// get the body
$('body').html();
Ad
source: stackoverflow.com
Ad