基于nodejs爬虫

本文介绍了如何使用Node.js进行爬虫开发,重点讲解了利用SuperAgent库进行接口和页面数据的抓取,以及Cheerio库对抓取的数据进行类似于jQuery的处理。通过实例演示了安装这两个模块并使用它们进行数据解析的过程。

爬接口数据

var https = require('https');
https.get('https://api.readhub.cn/topic?lastCursor=76823&pageSize=20',function(res,req){
var html='';
    res.on('data',function(data){
        html+=data;
    });
    res.on('end',function(){
        console.info(html);
})
console.log(html);
})

爬页面数据

var https = require('https');
const hupuUrl = 'https://bbs.hupu.com/selfie';
https.get(hupuUrl,function(res,req){
var html='';
    res.on('data',function(data){
        html+=data;
    });
    res.on('end',function(){
        console.info(html);
})
console.log(html);
})


另一种方式:
SuperAgent
superagent它是一个强大并且可读性很好的轻量级ajaxAPI,是一个关于HTTP方面的一个库,而且它可以将链式写法玩的出神入化
api res.text包含为被解析的响应数据

var superagent = require('superagent');
superagent .get('/api') //这里的URL也可以是绝对路径 
.end(function(req,res){ 
//do something 
//res.text包含为被解析的响应数据
})

superagent .get('/api') 
.set({ 'Referer':'https://www.google.com', 'Accept':'image/webp,image/*,*/*;q=0.8' })
 .end(function(req,res){ //do something })

cheerio
用法jQuery的用法差不多。
就是先将页面的数据load进来形成一个特定的数据格式,然后通过类似jq的语法,对数据进行解析处理)

var cheerio = require('cheerio'), 
$ = cheerio.load('<h2 class="title">Hello world</h2>');
 $('h2.title').text('Hello there!'); 
$('h2').addClass('welcome');


var superagent = require('superagent');
var cheerio = require('cheerio');

var url1 = 'https://www.dbmeinv.com/'
//这里的URL也可以是绝对路径
superagent.get(url1)
.end(function(req,res){
//do something
    console.log(res.text)

    $ = cheerio.load(res.text);
    console.log($('.height_min').length)
    $('.height_min').each(function(v,key){
        console.log(v,$(key).attr('src'));
    })


})

使用SuperAgent 和 cheerio具体例子
先安装 两个模块
npm i SuperAgent -S
npm i cheerio -S

var superagent = require('superagent');//引入superagent模块
var cheerio = require('cheerio');//引入cheerio模块
superagent .get('https://www.dbmeinv.com') //这里的URL也可以是绝对路径 
.end(function(req,res){ 
//do something 
//res.text包含为被解析的响应数据
console.log(res.text);
$ = cheerio.load(res.text);
$('.height_min').each(function(index,value){//找到页面中你想要的数据的类名.height_min,这里是图片的类名
    var src = $(value).attr('src');
    console.log(src);
})
})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值