node.js实战:爬取网站图片并下载保存

前言:
早就对node.js的爬虫“倾慕已久”,兜兜转转两三个月,又接触到了node.js。

话不多说,直接上代码

npm install request cheerio
const request = require('request')
const fs = require('fs')
const cheerio = require('cheerio')
request('http://cjxnsb.cn/mxc/UCgzs/1.html', function (error, response, body) {
    console.log('error:', error); // 错误优先
    console.log('statusCode:', response && response.statusCode);
    //获取爬取网站的页面信息
    const $ = cheerio.load(body)
    let imgs = []
    //目标网站图片链接地址数组
    // 用正则判断数组中的路径是否存在https
    var _ = /(http[s]?|ftp)/;
    $('img').each((i, e) => {  // 遍历所有
        var src = $(e).attr('src');

        if (!_.test(src)) {
            src = src.replace(/\/{2}/, 'https://')   //因为有些图片不可下载,所以用正则判断一下
        }
        imgs.push(src)
    })
    // 下载数组里的图片
    for (let index = 0; index < imgs.length; index++) {
        if (imgs[index].indexOf('http') !== -1) {
            request(imgs[index]).pipe(fs.createWriteStream(`./img/${index}.png`)) //这里为了省事,我就直接用下标命名了;
        }
    }
});

有几处需要注意的地方:

  1. 本demo只能爬取https网页图片,需要http的可以稍加改动
  2. cheerio:可以操作dom块,同jQuery写法
  3. 一定要提前新建img文件夹(图片保存路径),否则会出错!

本文仅供学习使用!

发布了195 篇原创文章 · 获赞 391 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43624878/article/details/103486732