使用node爬取表情包存进数据库

准备模块

使用的axios,cheerio,mysql模块都是第三方模块,需要提前下载

let mysql = require('mysql'),
    axios = require('axios'),
    cheerio = require('cheerio'),
    path = require('path'),
    fs = require('fs');

连接数据库

    let options = {
        host: 'localhost',
        port: '3306',
        user: 'root',
        password: '123456',
        database: 'imgs'
    };
    
    //创建连接对象
    let con = mysql.createConnection(options),
        count = 200,//爬取总的页数
        page = 1,//每次爬取的页
        index = 0;//每次递增的条数
    //建立连接
    con.connect(err => {
        if (err) {
            console.log(err); //查看是否有连接出错
        }
        console.log('连接成功');
    });

请求获取页面数据

    //获取第n个页面所有图片
    async function getImgUrl(num) {
        let baseUrl = 'https://www.fabiaoqing.com/biaoqing/lists/page/';//这里以发表情为例
        let res = await axios.get(baseUrl + num + '.html');
        // console.log(res.data);
        let $ = await cheerio.load(res.data);
        $('#bqb .segment .tagbqppdiv>a>.image').each((i, item) => {
            let href = $(item).attr('data-original'),
                title = $(item).attr('title');
            index++;
            // console.log(href, title);
            getInfo(index, title, href);//调取写入数据库函数
        });
    }

写入数据库并且保存在本地

async function getInfo(index, title, href) {
    let pathUrl = path.parse(href),
        ws = fs.createWriteStream(`./img/${pathUrl.base}`)
    await axios.get(href, { responseType: 'stream' }).then(res => {
        res.data.pipe(ws);
        // console.log('加载完成');
        res.data.on('close', () => {
            ws.close();
        })
    });
    let insert = 'insert into first (id,title,imgSrc,localImg) values (?,?,?,?)';//问号为占位符,可以在下面的query里传参,first为表名

    await (con.query(insert, [index, title, href, `./img/${pathUrl.base}`], (err, result, f) => {
        if (err) {
            console.log(err);
        }
        // console.log(result);
        // console.log(f)
    }));
    // // console.log(path.parse(href));
}

//使用递归获取所有页数的数据
async function getAll() {
    if (page > count) {
        page = index = count = null;
        return;
    }
    await getImgUrl(page);
    page++;
    return getAll();
}
getAll();

完毕,谢谢!最后可以断开数据库连接了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。