找传奇、传世资源到传世资源站!

nodejs 爬取豆瓣电影海报图片并下载到本地(async/await入门级示例)

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

nodejs async/await入门级示例
爬取结果如下:from clipboard
// import fs from 'fs';var fs = require('fs');var path = require('path');var request = require('request');var movieDir = __dirname '/movies', exts = ['.mkv', '.avi', '.mp4', '.rm', '.rmvb', '.wmv'];// 读取文件列表var readFiles = function () { return new Promise(function (resolve, reject) { fs.readdir(movieDir, function (err, files) { resolve(files.filter((v) => exts.includes(path.parse(v).ext))); }); });};// 获取海报var getPoster = function (movieName) { let url = `https://api.douban.com/v2/movie/search?q=${encodeURI(movieName)}`; return new Promise(function (resolve, reject) { request({url: url, json: true}, function (error, response, body) { if (error) return reject(error); resolve(body.subjects[0].images.large); }) });};// 保存海报var savePoster = function (movieName, url) { request.get(url).pipe(fs.createWriteStream(path.join(movieDir, movieName '.jpg')));};(async () => { let files = await readFiles(); // await只能使用在原生语法 for (var file of files) { let name = path.parse(file).name; console.log(`正在获取【${name}】的海报`); savePoster(name, await getPoster(name)); } console.log('=== 获取海报完成 ===');})();

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复