node爬虫 爬取图片

直接上代码:

//通过npm引入对应依赖
//不同协议引用不同模块,http https
const http = require('http')
const https = require('https')
const fs = require('fs')
const cheerio = require('cheerio')
let url = 'http://www.bbsnet.com' //网站地址
const saveFoldersPath = './images' //储存文件的文件夹地址
http.get(url, (res) => {
	//安全判断
	const {
		statusCode
	} = res //状态码
	const contentType = res.headers['content-type'] //数据类型
	let err = null
	if (statusCode !== 200) {
		err = new Error('请求状态错误' + statusCode)
	} else if (!/^text\/html/.test(contentType)) {
		err = new Error('请求类型错误' + contentType)
	}
	if (err) {
		console.log(err)
		res.resume() //清空缓存
		return false
	}

	// 判断images文件夹是否存在
	fs.exists(saveFoldersPath, (cb) => {
		!cb && fs.mkdir(saveFoldersPath, () => {})
	})

	//数据处理

	//数据分段,只要接受到数据就会触发data事件, chunk 每次接受的数据片段
	let rawData = ''
	res.on('data', (chunk) => {
		rawData += chunk.toString('utf-8') //使用utf-8的格式转码

	})
	//数据流传输完毕
	res.on('end', () => {
		//将请求的数据保存到本地
		let $ = cheerio.load(rawData) //使用jq的写法
		$('img').each((index, item) => {
			// console.log('item',$(item).attr('alt'))
			let name = ($(item).attr('alt') ? $(item).attr('alt') : index) + '.png'
			saveImg($(item).attr('src'), name)
		})
		console.log('数据传输完毕');

	})
}).on('error', (err) => {
	console.log('请求错误');
})
//保存图片到本地
function saveImg(url, name) {
	// console.log(url, name)
	try {
		http.get(url, function(req, res) {
			var imgData = '';
			req.setEncoding('binary');
			req.on('data', function(chunk) {
				imgData += chunk;
			})
			req.on('end', function() {
				fs.writeFile(`${saveFoldersPath}/${name}`, imgData, 'binary', function(err) {
					console.log('保存图片成功' + name)
				})
			})
		})
	} catch (err) {

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值