nodeJS简单版批量获取网页图片的方法

有时候想收集一些网站的图片,如果网页图片太多,一个个点击保存太耗费时间,
下面是一个基础版的获取图片网页的方法。

注意:只能获取固定写在html页面上的图片,不支持获取数据渲染的图片。

const http = require('http');  // 看网站区别是 http 还是 https
const cheerio = require('cheerio');  //类似jquery的工具
const HOST = 'https://www.xxx.com/'; 
const download = require('download');  //文件下载插件
const targetUrl = HOST + 'xx.html';   //页面地址
let req = http.request(targetUrl ,res=>{
        let chunks = [];
        res.on('data',c=>chunks.push(c));
        res.on('end',()=>{
            let htmlStr = Buffer.concat(chunks).toString('utf-8');
            const $ = cheerio.load(htmlStr);
            const target = 'img';  // 这是网页下的全部img 标签,如果需要特定排列的img,可以通过开发者工具查看dom的方法,获取特定的img; 比如 '.list .li>.img'
            const imgs = Array.prototype.map.call($(target),c=>HOST + encodeURI($(c).attr('src')))
            Promise.all(imgs.map(x=>download(x,'images'))).then(()=>{ //下载的图片放到images文件夹
                console.log('files downloaded') //完成之后调用
            })
        })
});
req.end()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值