JS 下载网络图片,并且修改图片名称
使用技术: NodeJS
gitHub地址: https://github.com/smallwhy/img-load-uptname
1、新建项目img-load-uptname
2、打开项目安装cheerio
npm install cheerio
3、安装request
npm install request
4、新建index.html
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<table border="1">
<tr>
<td>baidu-logo</td>
<td>https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png</td>
</tr>
<tr>
<td>baidu-bgimg-1</td>
<td>https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin/1.jpg</td>
</tr>
<tr>
<td>baidu-bgimg-2</td>
<td>https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin/2.jpg</td>
</tr>
</table>
</body>
</html>
5、新建load.js
const cheerio = require('cheerio');
var fs = require('fs');
var request = require('request');
// 读取输出到目录的所有文件名
let imgNames = []
const files = fs.readdirSync('./images-2')
files.forEach(function (item, index) {
imgNames.push(item);
});
console.log('images-2文件夹下的所有文件的文件名' + imgNames.join(','));
// 输出图片文件
fs.readFile("./index.html","utf-8",function(err,data){ // 读取文件index.html
if(err) {
console.log("index.html loading is failed :"+err);
}
else{
//返回index.html页面
var $ = cheerio.load(data); // data为index.html内容
var tr_list = $('table tr');
tr_list.each((index, item) => {
var imgName = $(item).find('td').eq(0).text(); // 下载文件的最终命名
var imgUrl = $(item).find('td').eq(1).text(); // 下载文件的URL
var writeStream = fs.createWriteStream('./imgs/'+imgName + imgUrl.substring(imgUrl.lastIndexOf('.'))); // 创建写入流
var readStream = request(imgUrl); // 读取流
readStream.pipe(writeStream);
readStream.on('end', function() { // 读取文件
console.log('文件下载成功');
});
readStream.on('error', function() {
console.log("错误信息:" + err)
});
writeStream.on("finish", function() { // 写入文件
console.log("文件写入成功");
writeStream.end();
});
});
}
});
6、新建存放下载图片的文件夹imgs
7、命令行执行load.js
node load.js
最终结果:
项目目录结构:
https://www.yuque.com/smallwhy?tab=books