使用cheerio拿一些数据

当网页中的数据找不到jsonp和ajax时,说明这个数据是后端写好了的,直接给前端的。所以没有数据请求。这时我们就拿不到数据了。但是可以使用node的cheerio模块,去爬取指定的数据。

代码如下:

(singleton.js)

小白发帖,有错误请指正

const https = require('https')

const cheerio = require('cheerio')

const mysql = require('mysql')

 

// 爬数据类

class MyCheerio {

​    constructor(requestConf) {

​        // 请求路径ulr

​        // 爬取的dom

​        const {

​            url,

​            element,

​            addSql,

​        } = requestConf

 

​        this.url = url;

​        this.element = element;

​        this.addSql = addSql;

		//用正则分离出sql语句的字段名作为爬取数据的名字
​        const reg = /\(([^)]*)\)/;

​        this.info = reg.exec(this.addSql)[1].split(',')

 

​        // 连接数据库
​        this.connection = '';
​        this.connerData()

​        // 获取爬取的数据
​        this.getHtml(this.url)

​    }

 

​    // 连接数据库(需要自己修改)

​    connerData() {

​        this.connection = mysql.createConnection({

​            host: 'localhost',

​            user: 'root',

​            password: '123456',

​            database: 'test'

​        })

​        this.connection.connect()

​    }

 

​    // 获取爬取的数据

​    getHtml(url) {

​        https.get(`${url}`, (res) => {

​            let htmlStr = '';

​            res.on('data', (chunk) => {

​                htmlStr += chunk;

​            })

​            res.on('error', (err) => {

​                console.log('err=', err);

​            })

​            res.on('end', () => {

​                this.spider(htmlStr)

​            })

​        })

 

​    }

 

​    // 爬取数据的方法

​    spider(htmlStr) {

​        const $ = cheerio.load(htmlStr, {

​            decodeEntities: false

​        });

​        $(`${this.element}`).each((index, ele) => {

 

​            // 打印遍历的标签

​            // console.log("element====", $(ele));

			
			//(需要自己去写获取的数据的Dom查询)
​            // 获取标签名

​            this.info[0] = $(ele).text().trim()

​            // 获取路径

​            this.info[1] = $(ele).find('a').attr('href');

​            // 获取当前获取时间

​            this.info[2] = new Date()


​            const addParmas = [this.info[0], this.info[1], this.info[2]];

			// 插入数据库
​            this.connection.query(this.addSql, addParmas, function (err, data) {

​                if (err) {

​                    console.log('数据库连接错误', err);

​                } else {

​                    console.log(index);

​                }

​            })

​        })

​    }

}

 

// 单例模式

const singleton = (function () {

​    let instance;

​    return function (confObj) {

​        if (!instance) {

​            instance = new MyCheerio(confObj)

​        }

​        return instance

​    }

})()


exports.singleton = singleton

使用方法:

(index.js)

// 使用方法

// 导入模块,设置参数confObj,调用模块singleton,需要自己去写获取的数据的Dom查询

 const {

​     singleton

 } = require('./singleton')

/**
- 向类中传入对象
- @param{url} 爬取数据的路径
- @param{element} 爬取数据的Dom标签
- @param{addSql} 插入数据库的语句
*/

const confObj = {

​    url: "https://www.csdn.net/",

​    element: '.host-move>ul>li',

​    addSql: 'insert into blog(title,href,time) values (?,?,?)'

}

// 调用
singleton(confObj)

得到结果如图:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值