岚岚天空

node.js图片下载器

岚岚天空 417 0
const download = require('download')
const axios = require('axios')
const fs = require('fs')
const path = require('path')

let headers = {
  'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
function sleep(time) {
  return new Promise((reslove) => setTimeout(reslove, time))
}

async function load(data) {
  await downloadFile(data)
  await sleep(3000)
  console.log('下载完成')
}


async function downloadFile(data) {
  for (let index =0; index < data.length; index++) {
    const item = data[index]
    const filename = item.img.split('/').pop();// 获取图片名称 .pop() 方法用于删除并返回数组的最后一个元素。
    const filePath = `${__dirname}/img`
    await download(item.img, filePath, {
      filename: filename,
      headers,
    }).then(() => {
      console.log(`Download ${index} 成功`)
      return
    }).catch((err) => {
        console.log(`Download ${index} 失败`)
        return
    })
  }
}

const data = [
    {img:'http://www.xxx.com/xxx1.jpg'},
    {img:'http://www.xxx.com/xxx2.jpg'}
]
load(data);

1、初始化

npm int -y

2、安装包

npm i axios download

3、运行

node index


本文标签: 爬虫 node

发表评论 (417人参与, 0 条评论)

评论列表

    快来评论,快来抢沙发吧~