>  기사  >  웹 프론트엔드  >  실용적인 공유: nodejs를 사용하여 10,000개 이상의 이미지를 크롤링하고 다운로드합니다.

실용적인 공유: nodejs를 사용하여 10,000개 이상의 이미지를 크롤링하고 다운로드합니다.

青灯夜游
青灯夜游앞으로
2022-03-24 19:49:284711검색

이 기사는 저자가 nodejs를 사용하여 10,000개 이상의 여동생 배경화면을 크롤링하는 방법을 볼 수 있는 node실제 경험을 공유할 것입니다. 모든 사람에게 도움이 되기를 바랍니다.

실용적인 공유: nodejs를 사용하여 10,000개 이상의 이미지를 크롤링하고 다운로드합니다.

안녕하세요 여러분 저는 Xiaoma입니다. 왜 이렇게 많은 사진을 다운로드해야 하나요? 며칠 전 uni-app + uniCloud를 사용하여 배경화면 애플릿을 무료로 배포했습니다. 그런 다음 애플릿의 콘텐츠를 채우려면 몇 가지 리소스가 필요합니다.

이미지 크롤링

먼저 프로젝트를 초기화하고 axios를 설치하면 cheerioaxioscheerio

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.jsrrreee

axios가 웹 콘텐츠를 크롤링하는 데 사용됩니다. Cherio는 서버 측의 jquery API입니다. 이를 사용하여 DOM에서 이미지 주소를 가져옵니다.

rrreee실용적인 공유: nodejs를 사용하여 10,000개 이상의 이미지를 크롤링하고 다운로드합니다.이 방법으로 페이지에서 이미지 URL을 가져올 수 있습니다. 다음으로 URL에 따라 이미지를 다운로드해야 합니다. 실용적인 공유: nodejs를 사용하여 10,000개 이상의 이미지를 크롤링하고 다운로드합니다.

nodejs를 사용하여 파일을 다운로드하는 방법

방법 1: 내장 모듈 'https' 및 ' fs'

nodejs

사용 내장 패키지나 타사 라이브러리를 사용하여 파일을 다운로드할 수 있습니다.

GET 메서드는 HTTPS를 통해 다운로드할 파일을 가져오는 데 사용됩니다. createWriteStream()은 쓰기 가능한 스트림을 생성하는 데 사용되는 메서드입니다. 이 메서드는 파일이 저장되는 위치인 하나의 매개변수만 받습니다. Pipe()는 읽기 가능한 스트림에서 데이터를 읽고 쓰기 가능한 스트림에 쓰는 메서드입니다.
rrreee

방법 2: DownloadHelper

rrreee🎜다음은 웹사이트에서 이미지를 다운로드하는 코드입니다. 객체 dl은 두 개의 매개변수를 받는 DownloadHelper 클래스에 의해 생성됩니다: 🎜
  1. 다운로드할 이미지.
  2. 다운로드 후 이미지를 저장해야 하는 경로입니다.
🎜File 변수에는 다운로드할 이미지의 URL이 포함되고, filePath 변수에는 저장될 파일의 ​​경로가 포함됩니다. 🎜rrreee🎜🎜방법 3: 다운로드 사용🎜🎜🎜은 npm의 달인입니다sindresorhus🎜작성되었으며 사용하기 매우 쉽습니다🎜rrreee🎜다음은 웹사이트에서 사진을 다운로드하는 코드입니다. 다운로드 기능은 파일과 파일 경로를 받습니다. 🎜rrreee

최종 코드🎜🎜원래 바이두 배경화면 크롤링하려고 했는데 해상도가 부족하고 워터마크 등이 있어서 나중에 그룹에 있던 친구가 API를 발견했어요 , 모바일 APP에서 고화질 배경화면으로 추정되며, 다운로드 URL을 직접 얻을 수 있어 직접 이용하였습니다. 🎜🎜다음은 전체 코드입니다🎜rrreee🎜위 코드에서 먼저 User-Agent를 설정하고 3초 지연을 설정해야 합니다. 이렇게 하면 서버가 크롤러를 차단하고 403을 직접 반환하는 것을 방지할 수 있습니다. 🎜🎜직접 node index.js하면 이미지가 자동으로 다운로드됩니다. 🎜🎜🎜, 🎜🎜🎜experience🎜🎜🎜WeChat 애플릿 검색 "🎜Watermelon Gallery🎜" 경험. 🎜🎜https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c5301b8b97094e92bfae240d7eb1ec5e~tplv-k3u1fbpfcp-zoom-1.awebp?🎜🎜🎜노드 관련 지식을 더 보려면 다음을 방문하세요: 🎜nodej 초 튜토리얼🎜 ! 🎜

위 내용은 실용적인 공유: nodejs를 사용하여 10,000개 이상의 이미지를 크롤링하고 다운로드합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제