需要安装第三方模块 mysql-ithm 和 crawler
代码
//导入模块
const hm=require('mysql-ithm')
const Crawler = require("crawler");
//1、抓包
var c = new Crawler({
maxConnections : 10,
// This will be called for each crawled page
callback : function (error, res, done) {
if(error){
console.log(error);
}else{
var $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
// console.log(JSON.parse(res.body))
/*王者荣耀所有的英雄,返回的是包含了很多对象的数组 */
//所有的英雄,都要去获取他对应的头像和技能
//所以要遍历出每一个英雄的ename,拼接一个路径重新发请求
JSON.parse(res.body).forEach((item)=>{
//console.log(`https;//pvp.qq.com/web201605/herodetaul/${item.ename}.shtml`)
//详情技能请求
xq.queue(`https://pvp.qq.com/web201605/herodetail/${item.ename}.shtml`)
})
}
done();
}
});
//存取英雄信息
let heros=[]
//创建一个英雄技能详情的信息的抓包
var xq = new Crawler({
maxConnections : 10,
// This will be called for each crawled page
callback : function (error, res, done) {
if(error){
console.log(error);
}else{
var $ = res.$;
// //英雄名字
// console.log($('.cover-name').text())
// // //英雄技能
// console.log($('.skill-name>b').first().text())
// // //英雄头像
// console.log('https:'+$('.ico-play').prev('img').attr('src'))
//增加英雄名字、英雄技能、英雄头像
heros.push({
name:$('.cover-name').text(),
skill:$('.skill-name>b').first().text(),
icon:'https:'+$('.ico-play').prev('img').attr('src'),
status:false
})
}
done();
}
});
//王者荣耀,页面人物信息数据抓取
// Queue just one URL, with default callback
c.queue('https://pvp.qq.com/web201605/js/herolist.json');
//要等待所有异步请求数据全部做完后,才开始入库
xq.on('drain',()=>{
// 调用API,插入数据
heroModel.insert(heros,(err,res)=>{
console.log(err)
console.log(res)
if(!err) console.log("成功添加√")
})
})
//2、连接数据库
//没有自动创建
hm.connect({
host:"localhost",
port:'3306',
user:'root',
password:'数据库密码',
database:'game'
})
//3、创建Model(表格模型,增删改查)
//如果table表格存在则连接,不存在则自动创建
//最好先创建好数据库和表,因为这个hm模块创建出来的表,再存入中文时会报错
//自己创建的数据库和表可以先设置为utf-8
let heroModel=hm.model('hero',{
name:String,
skill:String,
icon:String,
status:String
})