node cheerio爬虫图片

cherrio 获取html文档内容,操作和jquery一样

cnpm install cheerio -D

使用
let $=cheerio.load(请求来的html内容);

获取属性
$(dom对象/选择器).attr('属性');

图片的下载
(1)获取图片src地址
(2)通过流式请求src地址,获取图片
	axios.get(imgUrl,{responseType:'stream'}).then((res)=>{
		//responseType:'stream'  以流的形式返回
 		//返回的图片就是流式内容,可以直接用管道
 		res.data.pipe(ws);
 	})

爬取的网站

代码示例:

const cheerio =require('cheerio')
const axios =require('axios')
const fs=require('fs')
const path=require('path')

let http='https://www.doutula.com/'
axios.get(http).then((res)=>{
	let $=cheerio.load(res.data)

	//获取当前页面的所有表情包a标签链接
	$('#home .col-sm-9>a').each((index,item)=>{
		//获取所有表情包详情a标签href
		let pageUrl=$(item).attr('href');
		//获取表情包组的title
		let title=$(item).find('.random_title').text();
		//正则去掉标题中的时间戳
		let reg=/(.*?)\d/igs
		title=reg.exec(title)[1]
		//根据标题创建目录
		fs.mkdir('C:/Users/10853/Desktop/爬虫img'+'/'+title,function(err){
			console.log('ok');
		});
		//console.log(title);
		parsePage(pageUrl,title);
	})

})

//"C:\Users\10853\Desktop\爬虫img"


//通过a标签链接获取指定的img
async function parsePage(url,title){
	let res= await axios.get(url)
	let $=cheerio.load(res.data);
	$('.pic-content img').each((index,item)=>{
		//获得的是图片的地址,要想直接获得图片,还要创建流请求图片地址
		let imgUrl=$(item).attr('src');

	 	//获取图片后缀名
	 	let extName=path.extname(imgUrl);
	 	//创建写入流
	 	let ws=fs.createWriteStream('C:/Users/10853/Desktop/爬虫img/'+title+"/"+title+index+extName);
	 	//将图片流式写入,在请求的时候才能设置流式
	 	axios.get(imgUrl,{responseType:'stream'}).then((res)=>{
	 		//返回的图片就是流式内容,可以直接用管道
	 		res.data.pipe(ws);
	 	})
	 	
	 })
}

发布了550 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/104833796