溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么利用nodejs?爬取并下載一萬多張圖片

發(fā)布時間:2022-03-25 09:37:06 來源:億速云 閱讀:215 作者:小新 欄目:web開發(fā)

這篇文章主要為大家展示了“怎么利用nodejs爬取并下載一萬多張圖片”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“怎么利用nodejs爬取并下載一萬多張圖片”這篇文章吧。

爬取圖片

首先初始化項目,并且安裝 axioscheerio

npm init -y && npm i axios cheerio

axios 用于爬取網(wǎng)頁內(nèi)容,cheerio 是服務(wù)端的 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 了。接下來需要根據(jù) url 下載圖片。

如何使用 nodejs 下載文件

方式一:使用內(nèi)置模塊 ‘https’ 和 ‘fs’

使用 nodejs 下載文件可以使用內(nèi)置包或第三方庫完成。

GET 方法用于 HTTPS 來獲取要下載的文件。 createWriteStream() 是一個用于創(chuàng)建可寫流的方法,它只接收一個參數(shù),即文件保存的位置。Pipe()是從可讀流中讀取數(shù)據(jù)并將其寫入可寫流的方法。

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

下面是從網(wǎng)站下載圖片的代碼。一個對象 dl 是由類 DownloadHelper 創(chuàng)建的,它接收兩個參數(shù):

  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

下面是從網(wǎng)站下載圖片的代碼。下載函數(shù)接收文件和文件路徑。

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('下載完成')
  }
}

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 + '.jpeg',
      headers,
    }).then(() => {
      console.log(`Download ${item.id} Completed`)
      return
    })
  }
}

load()

上面代碼中先要設(shè)置 User-Agent 并且設(shè)置 3s 延遲, 這樣可以防止服務(wù)端阻止爬蟲,直接返回 403。

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

怎么利用nodejs?爬取并下載一萬多張圖片、怎么利用nodejs?爬取并下載一萬多張圖片

以上是“怎么利用nodejs爬取并下載一萬多張圖片”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI