哈喽,大家好,我是小马,为什么要下载这么多图片呢?前几天使用 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 imageconst 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 imageconst file = 'gfg.jpeg'// path at which image will be downloadedconst 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 imageconst file = 'gfg.jpeg'// path at which image will get downloadedconst 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爬取并下载一万多张图片的详细内容。
