No的.js 实现爬虫,王者荣耀英雄信息的爬取并存储到数据库中

32 篇文章 0 订阅
9 篇文章 0 订阅

需要安装第三方模块 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
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值