Node.js 如何使用nodejs抓取javascript(vuejs、reactjs)网站

Node.js 如何使用nodejs抓取javascript(vuejs、reactjs)网站,node.js,phantomjs,web-crawler,cheerio,Node.js,Phantomjs,Web Crawler,Cheerio,当我试图爬网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(er

当我试图爬网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);
我得到的内容如下

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

下次你们可能会想试试木偶师,我相信幻影不再存在了