一、思路概述
1、通过node内置的http/https模块获取指定网站html
2、通过第三方cheerio模块提取html中的所有img标签,所以运行前不要忘记
npm install cheerio
3、使用http/https请求所有img标签中的图片地址,并通过node内置的fs模块将返回的图片数据存储到文件系统中
二、源码
本例展示如何爬取w3cschool首页图片
// 用于发送http请求
const https = require('https')
const http = require('http')
// 用于提取网页中的img标签
const cheerio = require('cheerio')
// 用于将http响应中的数据写到文件中
const fs = require('fs')
// 用于获取系统文件分隔符
const path = require('path')
const sep = path.sep
// 用于存储图片和网页的文件夹路径
const imgDir = `${__dirname}${sep}imgs${sep}`
const pageDir = `${__dirname}${sep}pages${sep}`
// https协议名
const HTTPS = 'https:'
// 若文件夹不存在则创建
for (const dir of [imgDir, pageDir]) {
if (!fs.existsSync(dir)) {
console.log('文件夹(%s)不存在,即将为您创建', dir)
fs.mkdirSync(dir)
}
}
// const url = 'http://gee2dan.com/'
const url = 'https://www.w3cschool.cn/'
// 下载中的图片数量
let downloadingCount = 0
downloadImgsOn(url)
// 下载指定网站包含的图片
function downloadImgsOn(url) {
// URL作为options
const options = new URL(url);
// 获取协议
const protocol = options.protocol
// 根据协议选择发送请求的模块
const _http = protocol === HTTPS ? https : http
// 发送请求
const req = _http.request(options, (res) => {
// 用于存储返回的html数据
let htmlData = ''
res.on('data', (chunk) => {
htmlData += chunk.toString('utf8')
})
res.on('end', () => {
// 将html数据存储到文件中,可用于人工校验
const htmlFileName = `${pageDir}result.html`
fs.wri