node.js - 如何使用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);
但没有任何渲染。但是一个空白的网页。里面没有内容。
解决方案
我发现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();
推荐阅读
- java - 如何在 solaris OS 上的 weblogic 12.2.1.3 中添加 jars
- python - python子进程和wget询问密码
- swift - 如何同时更新 UICollectionViewCell 的边框并执行 UICollectionView Cells 的批量更新
- oracle - PRAGMA AUTONOMOUS_TRANSACTION 是什么意思?
- arrays - 在数组的子数组中查找公共元素
- ios - Xamarin:IOS geoLocator 中的监听问题
- java - 是否可以查询 Hazelcast 缓存?如果是,该怎么做?
- c++ - 递归代码以退出代码 3221225477 退出
- sql - 如何解决错误“无法对包含聚合或子查询的表达式执行聚合函数”
- python - 数据库中缺少字段但存在于 Django 的模型中