综述
本期就node爬虫做一个案列分享。因之前有过一点node学习,了解到node也是能作为爬虫工具使用的,因此成热打铁,赶紧尝试用node做了个爬虫。一来巩固自己基础知识,二是尝鲜。如今js(node本质还是js)能用做后端,而且还能做爬虫,以及未来得javascript面向硬件编程,震撼。 :)
开始
爬取目标
本次爬取的b站番剧封面图片。说明,爬取网站数据之前,先对爬取目标资源进行分析。
网站入口
https://www.bilibili.com/anime/index/
目标分析
有些网页图片资源是直接通过a > img ,图片的url是完整的url地址。而b站的图片的url就是相对的,通过后端请求,获取json得到img > url.如下
通过抓包获取数据接口
数据接口
https://api.bilibili.com/pgc/season/index/result?season_version=-1&area=-1&is_finish=-1©right=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&order=3&st=1&sort=0&page=1&season_type=1&pagesize=20&type=1
其中有这几个关键参数:page页数,pagesize每页数据条数
node爬取方式
-
方式一
根据node的三方模块cheerio,and http, fs通过类似jquery操作方式,获取页面超链接的href,发起批量请求,获取资源 -
方式二
就是我的爬虫中使用的方式。这种没有使用node 的cheerio三方模块,直接请求每个页面的数据接口得到数据,再拿到对应的图片url。再次图片url发起请求,爬到图片。
编程实现
通过最后分析我们采用方式二来编程实现图片资源爬取
源码
//导入moudle
const https = require('https');
const http = require('http');
const fs = require('fs');
function getData(){
return new Promise((resolve, rej) => {
var dateAll = null;
let Biurl = ' https://api.bilibili.com/pgc/season/index/result?season_version=-1&area=-1&is_finish=-1©right=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&order=3&st=1&sort=0&page=1&season_type=1&pagesize=20&type=1'
for(let i = 1; i < 149; i++){ //分页爬取
let url = ' https://api.bilibili.com/pgc/season/index/result?season_version=-1&area=-1&is_finish=-1©right=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&order=3&st=1&sort=0&page='+ i + '&season_type=1&pagesize=20&type=1'
https.get(url, function(res){
let date = '';
res.on('data', function(chunk){ //事件监听数据返回
date += chunk; //拼接服务器返回json,这里会自动转化为二进制buffer
});
res.on('end',function(){ //数据响应完成时触发
resolve(date);
//console.log(1,i);
});
}).on('error', function(e){
console.error(e.message);
});
//console.log(i)
}
});
};
var excuGet = getData();
excuGet.then(function(val){
var All = JSON.parse(val);
var list_img = (All.data).list;
var imgs_url = [];
var img_name = //;
list_img.forEach(element => {
imgs_url.push(element.cover);
});
for(let j = 0; j < imgs_url.
length; j++){
http.get(imgs_url[j], function(res){
var imgdata = '';
res.setEncoding("binary"); //设置response编码格式,否则下载的图片打不开
res.on('data', (chunk) => {
imgdata += chunk;
});
res.on('end', () => {
//写入文件
fs.writeFile('D:\\biliIMG\\'+ imgs_url[j].substr(-imgs_url[j].lastIndexOf('/'),27) + '.jpg', imgdata, 'binary',(err) => {
if (err) throw err;
console.log('The file has been saved!');
});
})
})
}
})
结果:
总结
可以看到 node爬虫实现还是挺简单的,短到百行代码不到,也可能是我的代码粗糙,实现不够严谨完整吧。这次爬虫大问题到是没有,唯一困忽悠到我的问题是,没有设置图片流的编码格式,导致下载的图片打不开。初次爬虫练习,希望对同行node初学者有所帮助。技术有限,文章代码不足之处,敬请指正。:)