cheerio爬取图片并保存到本地

百度的介绍:cheerio是nodejs的抓取页面模块,为服务器特别定制的,快速、灵活、实施的jQuery核心实现。适合各种Web爬虫程序。
今天就实验下,爬取图虫网的图片,不得不说。图虫网真的聚集好多优秀的摄影师,照片都感觉好好啊(没打广告),但是大部分的图片只能预览,无法下载。所以:
确定你要爬取的主题照片,现在以微风不燥 秋意正好这套照片为例子(教程十分具体化);
1.新建demo文件夹,创建tuchong.js。
然后用终端进入此文件夹。


cheerio爬取图片并保存到本地
文章图片
cheerio爬取图片并保存到本地
文章图片
2.此时在终端分别安装sync-request、cheerio、fs、request依赖,
命令行分别执行npm install sync-request/cheerio/fs/request
3.打开网站,调试,你会发现所有的图片都放在此dom下


cheerio爬取图片并保存到本地
文章图片
dom:$("article.post-content") 因为我们需要创建文件夹,所以我们拿到这组图的主题名字


cheerio爬取图片并保存到本地
文章图片
dom:$("title") 上代码(代码的注释挺详细):

const fs = require('fs') //创建文件、文件夹
const cheerio = require('cheerio') //cheerio爬虫
const requests = require('sync-request') //node的网络请求
const request = require('request') //利用request模块保存图片
var html = '';
【cheerio爬取图片并保存到本地】let count = 0 // 记录扒取的图片数量
let imgDirName = '' // 图片存放的目录
let url = "https://tuchong.com/443122/15624611/"; // 目标网站
// 拿到网站内容转化成html字符串
html = requests('GET', url).getBody().toString();
console.log(html)
// 调用自己的方法
filterSlideList(html)
function filterSlideList(html) {
if (html) {
var $ = cheerio.load(html); // 利用cheerio模块将完整的html装载到变量$中,之后就可以像jQuery一样操作html了
// 拿到图片的父容器
var $imgdom = $("article.post-content");
// 拿到主题,并使用主题名字(名字太长,截取一下)创建文件夹
var imgarrname = $("title").text().substr(0, 5);
console.log("开始爬 " + imgarrname + " 主题的图片")
//创建放图片的文件夹
fs.mkdir('./img/' + imgarrname + '/', (err) => {
if (err) {
console.log(err)
}
})
//取每一张图片,并把图片放到目录下
$imgdom.find('img').each(function(index, el) {
var imgurl = $(this).attr("src"), //拿到图片的在线链接
imgnam = $(this).attr("alt"), //拿到图片的标题
imgid = $(this).attr("id"); //图片名字有可能重复,取到唯一id
// 利用request模块保存图片
request(imgurl).pipe(fs.createWriteStream('./img/' + imgarrname + '/' + imgnam + imgid + '.jpg'))
// '''''''''''''''''''''''''''''''''''''''''''''''''图片目录'''''''''''''拼接的图片名'''''
count++;
console.log(imgurl);
console.log(imgnam);
console.log('已爬取图片' + count + '张');
});
}
}
3.执行node tuchong.js


爬取成功

    推荐阅读