本篇介绍利用第3方的request和cheerio模块实现抓取网页图片到本地的功能。
首先,创建项目工程Crawling,并创建package.json文件来管理与安装该项目依赖的模块包。
其次,安装第3方模块包request和cheerio包
准备工作完成后,现在来编写代码:
/**
* 抓取网页图片
*/
//载入第3方request模块
const request = require("request");
//载入第3方cheerio模块
const cheeric = require("cheerio");
//载入内置path模块
const path = require("path");
//载入内置fs模块
const fs = require("fs");
//测试抓取图片的网页地址
const testImageUrl = "http://www.qingdoanews.com";
//抓取到的图片本地保存路径
const downloadImagePath = path.join(__dirname,"downloadImages");
//开始抓取目标网址页的图片请求
request(testImageUrl,function(err,res,body){
if(!err && res)
{
let $ = cheeric.load(body);//加载网页
$("img").each(function(i,elem){//遍历文档中所有图片标签
let imgSrc = $(this).attr("src");//获取图片的url
console.log("当前抓取的图片下载url:",imgSrc);
let filName = imgSrc.split('/').pop();
//使用request模块读取流直接写入fs写入流
if(imgSrc.startsWith("http"))
request.get(imgSrc).pipe(fs.createWriteStream(path.join(downloadImagePath,filName), { 'encoding': 'utf8' }));
});
}else
{
console.log(err);
}
});
运行结果如下:
注意:当前编写的工具只能抓取解析图片url地址:
https://qingdoanews.com/wp-content/uploads/2019/02/cropped-Qingdao.jpg
这样的图片,前面是http开头,以图片格式结尾的图片url。