首页 > 解决方案 > 如何使用nodejs爬取javascript(vuejs,reactjs)网站

问题描述

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

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

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

标签: node.jsphantomjsweb-crawlercheerio

解决方案


我发现cheerio 不运行javascript。因为这个基于 vue 前端的网站我需要一个虚拟浏览器来实际运行 js 并为我呈现输出

所以request我没有使用幻像来渲染 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();

推荐阅读