如何用nodejs爬取javascript(vuejs,reactjs)网站

How to crawl javascript (vuejs, reactjs) web site with nodejs

我正打算抓取 vue js 前端网站,当我尝试抓取它不会将内容加载到 cheerio.. 我得到的是一个空白网页。我的代码如下

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});
    });
  })
}

我得到的内容如下

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);

但是没有渲染任何东西。但是一个空白网页。里面没有内容。

我发现 cheerio 没有 运行 javascript。由于这个网站基于 vue 前端,我需要一个虚拟浏览器,它实际上 运行 js 并为我呈现输出

所以我没有使用request而是使用phantom来渲染js网页

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};
} 

现在我可以得到如下所示的渲染页面

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