node爬虫爬取网站图片

// 爬虫
const https = require('https')
const fs = require('fs')
const cheerio = require('cheerio')
const url = require('url')

const site = 'https://www.xxx.com/'
const saveFoldersPath = './images'

https.get(site, res => {
  let err = ''
  if (res.statusCode != 200) {
    err = new Error('请求失败')
  }
  // 判断请求格式是否是网页
  if (!/^text\/html/.test(res.headers['content-type'])) { // 格式不是网页
    err = new Error('请求格式不是网页')
  }

  if (err) {
    res.resume() // 重置缓存
    return
  }

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

  let str = ''
  // 数据是分段的
  res.on('data', chunk => {
    str += chunk
  })
  // 数据获取完成
  res.on('end', () => {
    // fs.writeFileSync('./bili.html', str)
    let $ = cheerio.load(str)
    $('img').each((index, el) => {
      let imgSrc = $(el).attr('src')
      // 此时需要做处理
      if (!imgSrc.startsWith('http://') && !imgSrc.startsWith('https://')) {
        imgSrc = url.parse(site).protocol + imgSrc
      }
      downLoad(imgSrc)
    })
  })
}).on('error', (e) => {
  console.error(e);
});

function downLoad(imgUrl) {
  https.get(imgUrl, (res) => {
    // 必须要设置,如果不设置,下载的图片可能打不开
    res.setEncoding('binary')
    let imgData = ''
    res.on('data', (chunk) => {
      imgData += chunk
    })
    res.on('end', () => {
      // 获取文件信息
      let files = parseFile(imgUrl)
      // 过滤掉不是.jpg|.png|.gif结尾的imgSrc
      if (files[1] == 'jpg' || files[1] == 'JPG' || files[1] == 'png' || files[1] == 'PNG' || files[1] == 'GIF' || files[1] == 'gif') {
        // 下载图片
        fs.writeFile(`${saveFoldersPath}/${files.join('.')}`, imgData, 'binary', (err) => {
          if (err) {
            console.log('dowload fail', err)
          } else {
            console.log('download success')
          }
        })
      }
    })
  })
}

function parseFile(imgUrl) {
  let urls = imgUrl.split('/')
  let fileName = urls[urls.length - 1]
  return fileName.split('.')
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值