【问题标题】:How to crawl javascript (vuejs, reactjs) web site with nodejs如何使用nodejs爬取javascript(vuejs,reactjs)网站
【发布时间】:2019-02-02 11:37:14
【问题描述】:

当我尝试爬取 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);

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

【问题讨论】:

    标签: node.js phantomjs web-crawler cheerio


    【解决方案1】:

    我发现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();
    

    【讨论】:

    • 下次可以试试puppeteer,相信phantomjs已经不再维护了
    猜你喜欢
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多