在互联网时代,图片是信息传递和展示的重要组成部分,而提取网页中的图片数据对于一些项目和需求来说尤为重要。本文将详细介绍如何使用Node.js编写爬虫程序,实现网页图片的批量爬取,帮助您轻松获得所需的图片数据,并揭示一些实用技巧和注意事项。
一、准备工作
npm init -y
npm install axios cheerio fs path
二、实现爬虫程序
crawler.js文件,并在文件头部导入需要的依赖:const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
fetchPage函数,用于发起HTTP请求并获取网页内容:async function fetchPage(url) {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(error);
throw new Error('Failed to fetch the page');
}
}
cheerio库来解析网页内容,提取其中的图片链接:function extractImageUrls(html) {
const $ = cheerio.load(html);
const imageUrls = [];
$('img').each((index, element) => {
const src = $(element).attr('src');
// 对图片链接进行处理,补全相对路径等
const imageUrl = new URL(src, 'http://example.com').href;
imageUrls.push(imageUrl);
});
return imageUrls;
}
downloadImage函数,用于下载图片到本地:async function downloadImage(url, savePath) {
try {
const response = await axios.get(url, { responseType: 'stream' });
const filePath = path.join(savePath, path.basename(url));
const writer = fs.createWriteStream(filePath);
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
} catch (error) {
console.error(error);
throw new Error('Failed to download the image');
}
}
async function main() {
const url = 'http://example.com'; // 替换为需要爬取的网页URL
const savePath = path.join(__dirname, 'images');
try {
const html = await fetchPage(url);
const imageUrls = extractImageUrls(html);
fs.mkdirSync(savePath, { recursive: true });
for (const imageUrl of imageUrls) {
await downloadImage(imageUrl, savePath);
console.log('Downloaded:', imageUrl);
}
} catch (error) {
console.error(error);
}
}
main();
三、运行程序与注意事项
node crawler.js
axios库发起HTTP请求、cheerio库解析网页内容,并结合fs和path模块实现图片的下载,您可以轻松地获取所需的图片数据。。希望本文的内容能够帮助您在实际项目中应用爬虫技术,提升您的工作效率和数据采集能力。