爬接口数据
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('Hello world
');
$('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);
})
})