首頁  >  文章  >  web前端  >  實戰分享:利用nodejs爬取並下載一萬多張圖片

實戰分享:利用nodejs爬取並下載一萬多張圖片

青灯夜游
青灯夜游轉載
2022-03-24 19:49:284718瀏覽

這篇文章給大家分享一個node實戰,看看作者是如何用 nodejs 爬了一萬多張小姐姐壁紙的,希望對大家有所幫助!

實戰分享:利用nodejs爬取並下載一萬多張圖片

哈嘍,大家好,我是小馬,為什麼要下載這麼多圖片? 前幾天使用 uni-app uniCloud 免費部署了一個壁紙小程序,那麼接下來就需要一些資源,為小程式填充內容。

爬取圖片

先初始化項目,並且安裝axioscheerio

npm init -y && npm i axios cheerio

axios用於爬取網頁內容,cheerio 是服務端的jquery api, 我們用它來獲取dom 中的圖片地址;

const axios = require('axios')
const cheerio = require('cheerio')

function getImageUrl(target_url, containerEelment) {
  let result_list = []
  const res = await axios.get(target_url)
  const html = res.data
  const $ = cheerio.load(html)
  const result_list = []
  $(containerEelment).each((element) => {
    result_list.push($(element).find('img').attr('src'))
  })
  return result_list
}

這樣就可以獲取到頁面中的圖片url 了。接下來要根據 url 下載圖片。

如何使用nodejs 下載檔案

方式一:使用內建模組'https' 和'fs'

使用nodejs 下載檔案可以使用內建套件或第三方函式庫完成。

GET 方法用於 HTTPS 來取得要下載的檔案。 createWriteStream() 是一個用來建立可寫流的方法,它只接收一個參數,也就是檔案保存的位置。 Pipe()是從可讀流讀取資料並將其寫入可寫流的方法。

const fs = require('fs')
const https = require('https')

// URL of the image
const url = 'GFG.jpeg'

https.get(url, (res) => {
  // Image will be stored at this path
  const path = `${__dirname}/files/img.jpeg`
  const filePath = fs.createWriteStream(path)
  res.pipe(filePath)
  filePath.on('finish', () => {
    filePath.close()
    console.log('Download Completed')
  })
})

方式二:DownloadHelper

#
npm install node-downloader-helper

以下是從網站下載圖片的程式碼。一個物件 dl 是由類別 DownloadHelper 建立的,它接收兩個參數:

  1. 將要下載的映像。
  2. 下載後必須儲存映像的路徑。

File 變數包含將要下載的映像的 URL,filePath 變數包含將要儲存檔案的路徑。

const { DownloaderHelper } = require('node-downloader-helper')

// URL of the image
const file = 'GFG.jpeg'
// Path at which image will be downloaded
const filePath = `${__dirname}/files`

const dl = new DownloaderHelper(file, filePath)

dl.on('end', () => console.log('Download Completed'))
dl.start()

方法三: 使用download

#是npm 大神sindresorhus 寫的,非常好用

npm install download

下面是從網站下載圖片的程式碼。下載函數接收檔案和檔案路徑。

const download = require('download')

// Url of the image
const file = 'GFG.jpeg'
// Path at which image will get downloaded
const filePath = `${__dirname}/files`

download(file, filePath).then(() => {
  console.log('Download Completed')
})

最終代碼

本來想去爬百度壁紙,但是清晰度不太夠,而且還有水印等,後來, 群裡有個小夥伴找到了一個api,估計是某支手機APP 上的高畫質桌布,可以直接取得下載的url,我就直接用了。

下面是完整程式碼

const download = require('download')
const axios = require('axios')

let headers = {
  'User-Agent':
    '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',
}

function sleep(time) {
  return new Promise((reslove) => setTimeout(reslove, time))
}

async function load(skip = 0) {
  const data = await axios
    .get(
      'http://service.picasso.adesk.com/v1/vertical/category/4e4d610cdf714d2966000000/vertical',
      {
        headers,
        params: {
          limit: 30, // 每页固定返回30条
          skip: skip,
          first: 0,
          order: 'hot',
        },
      }
    )
    .then((res) => {
      return res.data.res.vertical
    })
    .catch((err) => {
      console.log(err)
    })
  await downloadFile(data)
  await sleep(3000)
  if (skip < 1000) {
    load(skip + 30)
  } else {
    console.log(&#39;下载完成&#39;)
  }
}

async function downloadFile(data) {
  for (let index = 0; index < data.length; index++) {
    const item = data[index]

    // Path at which image will get downloaded
    const filePath = `${__dirname}/美女`

    await download(item.wp, filePath, {
      filename: item.id + &#39;.jpeg&#39;,
      headers,
    }).then(() => {
      console.log(`Download ${item.id} Completed`)
      return
    })
  }
}

load()

上面程式碼中先要設定 User-Agent 並且設定 3s 延遲, 這樣可以防止服務端阻止爬蟲,直接傳回 403。

直接 node index.js 就會自動下載圖片了。

實戰分享:利用nodejs爬取並下載一萬多張圖片實戰分享:利用nodejs爬取並下載一萬多張圖片

體驗

微信小程式搜尋 「西瓜圖庫」體驗。

https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c5301b8b97094e92bfae240d7eb1ec5e~tplv-k3u1fbpfcp-z#-1.awebp?oom##nodep相關知識,請造訪:

nodejs 教學

以上是實戰分享:利用nodejs爬取並下載一萬多張圖片的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除