实战分享:利用nodejs​爬取并下载一万多张图片

 4580

本篇文章给大家分享一个node实战,看看作者是如何用 nodejs 爬了一万多张小姐姐壁纸的,希望对大家有所帮助!


实战分享:利用nodejs​爬取并下载一万多张图片


哈喽,大家好,我是小马,为什么要下载这么多图片呢? 前几天使用 uni-app + uniCloud 免费部署了一个壁纸小程序,那么接下来就需要一些资源,给小程序填充内容。

爬取图片

首先初始化项目,并且安装 axios 和 cheerio

  1. npm init -&& npm i axios cheerio

axios 用于爬取网页内容,cheerio 是服务端的 jquery api, 我们用它来获取 dom 中的图片地址;

  1. const axios = require('axios')
  2. const cheerio = require('cheerio')
  3.  
  4. function getImageUrl(target_url, containerEelment) {
  5.   let result_list = []
  6.   const res = await axios.get(target_url)
  7.   const html = res.data
  8.   const $ = cheerio.load(html)
  9.   const result_list = []
  10.   $(containerEelment).each((element) => {
  11.     result_list.push($(element).find('img').attr('src'))
  12.   })
  13.   return result_list
  14. }

这样就可以获取到页面中的图片 url 了。接下来需要根据 url 下载图片。

如何使用 nodejs 下载文件

方式一:使用内置模块 ‘https’ 和 ‘fs’

使用 nodejs 下载文件可以使用内置包或第三方库完成。

GET 方法用于 HTTPS 来获取要下载的文件。 createWriteStream() 是一个用于创建可写流的方法,它只接收一个参数,即文件保存的位置。Pipe()是从可读流中读取数据并将其写入可写流的方法。

  1. const fs = require('fs')
  2. const https = require('https')
  3.  
  4. // URL of the image
  5. const url = 'GFG.jpeg'
  6.  
  7. https.get(url, (res) => {
  8.   // Image will be stored at this path
  9.   const path = `${__dirname}/files/img.jpeg`
  10.   const filePath = fs.createWriteStream(path)
  11.   res.pipe(filePath)
  12.   filePath.on('finish', () => {
  13.     filePath.close()
  14.     console.log('Download Completed')
  15.   })
  16. })


方式二:DownloadHelper

  1. npm install node-downloader-helper

下面是从网站下载图片的代码。一个对象 dl 是由类 DownloadHelper 创建的,它接收两个参数:

将要下载的图像。

下载后必须保存图像的路径。

File 变量包含将要下载的图像的 URL,filePath 变量包含将要保存文件的路径。

  1. const { DownloaderHelper } = require('node-downloader-helper')
  2.  
  3. // URL of the image
  4. const file = 'GFG.jpeg'
  5. // Path at which image will be downloaded
  6. const filePath = `${__dirname}/files`
  7.  
  8. const dl = new DownloaderHelper(file, filePath)
  9.  
  10. dl.on('end', () => console.log('Download Completed'))
  11. dl.start()


方法三: 使用 download

是 npm 大神 sindresorhus 写的,非常好用

  1. npm install download

下面是从网站下载图片的代码。下载函数接收文件和文件路径。

  1. const download = require('download')
  2.  
  3. // Url of the image
  4. const file = 'GFG.jpeg'
  5. // Path at which image will get downloaded
  6. const filePath = `${__dirname}/files`
  7.  
  8. download(file, filePath).then(() => {
  9.   console.log('Download Completed')
  10. })

最终代码

本来想去爬百度壁纸,但是清晰度不太够,而且还有水印等,后来, 群里有个小伙伴找到了一个 api,估计是某个手机 APP 上的高清壁纸,可以直接获得下载的 url,我就直接用了。

下面是完整代码

  1. const download = require('download')
  2. const axios = require('axios')
  3.  
  4. let headers = {
  5.   'User-Agent':
  6.     'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
  7. }
  8.  
  9. function sleep(time) {
  10.   return new Promise((reslove) => setTimeout(reslove, time))
  11. }
  12.  
  13. async function load(skip = 0) {
  14.   const data = await axios
  15.     .get(
  16.       'http://service.picasso.adesk.com/v1/vertical/category/4e4d610cdf714d2966000000/vertical',
  17.       {
  18.         headers,
  19.         params: {
  20.           limit: 30, // 每页固定返回30条
  21.           skip: skip,
  22.           first: 0,
  23.           order: 'hot',
  24.         },
  25.       }
  26.     )
  27.     .then((res) => {
  28.       return res.data.res.vertical
  29.     })
  30.     .catch((err) => {
  31.       console.log(err)
  32.     })
  33.   await downloadFile(data)
  34.   await sleep(3000)
  35.   if (skip < 1000) {
  36.     load(skip + 30)
  37.   } else {
  38.     console.log('下载完成')
  39.   }
  40. }
  41.  
  42. async function downloadFile(data) {
  43.   for (let index = 0; index < data.length; index++) {
  44.     const item = data[index]
  45.  
  46.     // Path at which image will get downloaded
  47.     const filePath = `${__dirname}/美女`
  48.  
  49.     await download(item.wp, filePath, {
  50.       filename: item.id + '.jpeg',
  51.       headers,
  52.     }).then(() => {
  53.       console.log(`Download ${item.id} Completed`)
  54.       return
  55.     })
  56.   }
  57. }
  58.  
  59. load()

上面代码中先要设置 User-Agent 并且设置 3s 延迟, 这样可以防止服务端阻止爬虫,直接返回 403。

直接 node index.js 就会自动下载图片了。


实战分享:利用nodejs​爬取并下载一万多张图片
实战分享:利用nodejs​爬取并下载一万多张图片

本文网址:https://www.zztuku.com/detail-11371.html
站长图库 - 实战分享:利用nodejs​爬取并下载一万多张图片
申明:本文转载于《掘金社区》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐