实战分享:利用nodejs爬取并下载一万多张图片
本篇文章给大家分享一个node实战,看看作者是如何用 nodejs 爬了一万多张小姐姐壁纸的,希望对大家有所帮助!
哈喽,大家好,我是小马,为什么要下载这么多图片呢? 前几天使用 uni-app + uniCloud 免费部署了一个壁纸小程序,那么接下来就需要一些资源,给小程序填充内容。
爬取图片
首先初始化项目,并且安装 axios
和 cheerio
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 创建的,它接收两个参数:
- 将要下载的图像。
- 下载后必须保存图像的路径。
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('下载完成') } } 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()
上面代码中先要设置 User-Agent
并且设置 3s 延迟, 这样可以防止服务端阻止爬虫,直接返回 403。
直接 node index.js
就会自动下载图片了。
、
体验
微信小程序搜索 “西瓜图库” 体验。
https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/c5301b8b97094e92bfae240d7eb1ec5e~tplv-k3u1fbpfcp-zoom-1.awebp?
更多node相关知识,请访问:nodejs 教程!
以上是实战分享:利用nodejs爬取并下载一万多张图片的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

Node.js 有 LTS 版本和 Current 版本,这两种版本有什么区别?下面本篇文章带大家快速掌握 Node.js 版本的区别,并聊聊如何选择合适的版本,希望对大家有所帮助!

Node.js 的是一门单线程的语言,它基于 V8 引擎开发,v8 在设计之初是在浏览器端对 JavaScript 语言的解析运行引擎,其最大的特点是单线程,这样的设计避免了一些多线程状态同步问题,使得其更轻量化易上手。

Node.js如何进行版本管理?下面本篇文章给大家整理分享3 款非常实用的 Node.js 版本管理工具,希望对大家有所帮助!

npm 是 JavaScript世界的包管理工具,并且是 Node.js平台的默认包管理工具。通过 npm可以安装、共享、分发代码,管理项目依赖关系。本篇文章带大家了解一下npm的原理,希望对大家有所帮助!

IDEA中怎么运行node?下面本篇文章给大家介绍一下IDEA中配置安装并运行node.js的方法,希望对大家有所帮助!

Node.js 如何实现异步资源上下文共享?下面本篇文章给大家介绍一下Node实现异步资源上下文共享的方法,聊聊异步资源上下文共享对我们来说有什么用,希望对大家有所帮助!

本篇文章通过读写文件和处理路径的案例,来一起学习下Node中的fs文件模块和path路径模块,希望对大家有所帮助!

二维码在生活中无处不在,之前我也使用过java的zxing库生成过二维码,功能很强大。但是其实nodejs上也有很多第三方库能够生成二维码。今天我们就是使用qrcode这个库来生成二维码。
