利用node.js爬取指定排名网站的JS引用库详解(2)

$(function () { var query = $('.query'), rank = $('.rank'), show = $('.show'), queryLib = $('.queryLib'), libShow = $('#libShow'), libName = $('.libName'), displayResult = $('.displayResult'); var checkLib = (function(){ function _query(){ query.click(function(){ $.post( '/query', { rank: rank.val(), }, function(data){ console.log(data); } ) }); queryLib.click(function(){ var inputLibName = libName.val(); if (inputLibName.length == 0) { alert('请输入库名~'); return; } $.post( '/queryLib', { libName: inputLibName, }, function(data){ if(data.length == 0){ alert('没有查询到名为' + inputLibName + '的库'); libName.val(''); libName.focus(); libShow.html('') return; } var libHtml = ''; for (var i = 0; i < data.length; i++) { libHtml += '<tr><td>'; libHtml += (i+1) + '</td><td>'; libHtml += data[i].name + '</td><td>'; libHtml += data[i].libsNum + '</td></tr>'; } libShow.html(libHtml); } ) }); } function _showLibs(){ show.click(function(){ $.get( '/getLibs', { rank: rank.val(), }, function(data){ console.log('一共返回'+ data.length + '条数据'); console.log(data) var libHtml = ''; for (var i = 0; i < 20; i++) { libHtml += '<tr><td>'; libHtml += (i+1) + '</td><td>'; libHtml += data[i].name + '</td><td>'; libHtml += data[i].libsNum + '</td></tr>'; } displayResult.show(); libShow.html(libHtml);// 点击显示按钮,显示前20项数据 _paging(data); } ) }); } //翻页器 function _paging(libObj) { var ele = $('#page'); var pages = Math.ceil(libObj.length/20); console.log('总页数' + pages); ele.bootstrapPaginator({ currentPage: 1, totalPages: pages, size:"normal", bootstrapMajorVersion: 3, alignment:"left", numberOfPages:pages, itemTexts: function (type, page, current) { switch (type) { case "first": return "首页"; case "prev": return "上一页"; case "next": return "下一页"; case "last": return "末页"; case "page": return page; } }, onPageClicked: function(event, originalEvent, type, page){ // console.log('当前选中第:' + page + '页'); var pHtml = ''; var endPage; var startPage = (page-1) * 20; if (page < pages) { endPage = page * 20; }else{ endPage = libObj.length; } for (var i = startPage; i < endPage; i++) { pHtml += '<tr><td>'; pHtml += (i+1) + '</td><td>'; pHtml += libObj[i].name + '</td><td>'; pHtml += libObj[i].libsNum + '</td></tr>'; } libShow.html(pHtml); } }) } function init() { _query(); _showLibs(); } return { init: init } })(); checkLib.init(); })

2.后端路由

var express = require('express'); var mongoose = require('mongoose'); var request = require('request'); var cheerio =require('cheerio'); var router = express.Router(); var JsLib = require('../model/jsLib') /* 显示主页 */ router.get('https://www.jb51.net/', function(req, res, next) { res.render('index'); }); // 显示库 router.get('/getLibs',function(req,res,next){ JsLib.find({}) .sort({'libsNum': -1}) .exec(function(err,data){ res.json(data); }) }) // 库的查询 router.post('/queryLib',function(req,res,next){ var libName = req.body.libName; JsLib.find({ name: libName }).exec(function(err,data){ if (err) console.log('查询出现错误' + err); res.json(data); }) }) router.post('/query',function(req,res,next) { var rank = req.body.rank; var len = Math.round(rank/20); for (var i = 1; i < len+1; i++) { (function(i){ var options = { url: 'http://www.alexa.cn/siterank/' + i, headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' } }; request(options, function (err, response, body) { analyData(body,rank); }) })(i) } res.json('保存成功') }) var sites = []; var flag = 0; function analyData(data,rank) { if(data.indexOf('html') == -1) return false; var $ = cheerio.load(data);// 传递 HTML var sitesArr = $('.info-wrap .domain-link a').toArray();//将所有a链接存为数组 console.log('网站爬取中``') for (var i = 0; i < 10; i++) { // ***这里后面要改,默认爬取前10名 var url = sitesArr[i].attribs.href; sites.push(url);//保存网址,添加wwww前缀 } console.log(sites); console.log('一共爬取' + sites.length +'个网站'); console.log('存储数据中...') getScript(sites); } // 获取JS库文件地址 function getScript(urls) { var scriptArr = []; var src = []; var jsSrc = []; for (var j = 0; j < urls.length; j++) { (function(i,callback){ var options = { url: urls[i], headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36' } } request(options, function (err, res, body) { if(err) console.log('出现错误: '+err); var $ = cheerio.load(body); var scriptFile = $('script').toArray(); callback(scriptFile,options.url); }) })(j,storeLib) }; function storeLib(scriptFile,url){ flag++;// 是否存储数据的标志 scriptFile.forEach(function(item,index){ if (item.attribs.src != null) { obtainLibName(item.attribs.src,index); } }) function obtainLibName(jsLink,i){ var reg = /[^\/\\]+$/g; var libName = jsLink.match(reg).join(''); var libFilter = libName.slice(0,libName.indexOf('.')); src.push(libFilter); } // console.log(src.length); // console.log(calcNum(src).length) (function(len,urlLength,src){ // console.log('length is '+ len) if (len == 10 ) {// len长度为url的长度才向src和数据库里存储数据,防止重复储存 // calcNum(src);//存储数据到数据库 // ***这里后面要改,默认爬取前10名 var libSrc = calcNum(src); store2db(libSrc); } })(flag,urls.length,src) } }// getScript END // 将缓存数据存储到数据库 function store2db(libObj){ console.log(libObj); for (var i = 0; i < libObj.length; i++) { (function(i){ var jsLib = new JsLib({ name: libObj[i].lib, libsNum: libObj[i].num }); JsLib.findOne({'name': libObj[i].lib},function(err,libDoc){ if(err) console.log(err); // console.log(libDoc) if (!libDoc){ jsLib.save(function(err,result){ if(err) console.log('保存数据出错' + err); }); } }) })(i) } console.log('一共存储' + libObj.length + '条数据到数据库'); } // JS库排序算法 function calcNum(arr){ var libObj = {}; var result = []; for (var i = 0, len = arr.length; i < len; i++) { if (libObj[arr[i]]) { libObj[arr[i]] ++; } else { libObj[arr[i]] = 1; } } for(var o in libObj){ result.push({ lib: o, num: libObj[o] }) } result.sort(function(a,b){ return b.num - a.num; }); return result; } module.exports = router;

源码下载

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyjgfx.html