node.js基础学习-cheerio模块-简单小爬虫(五)

学习cheerio模块,简单做一个爬取图片网站的图片,并且将这些图片下载到本地指定的文件夹下,很多图片网站都有一些反爬取的机制,找的好几个都会报302错误,所以我找了一个小的图片网站,这个没有反爬取机制,实现了一下,最后成功获取并下载到了图片,以下就是全部的完整代码,也不做太详细的记录了。

完整的爬取图片代码如下:

js 复制代码
const https = require('https');
const request = require('request');
const fs = require('fs');
const cheerio = require("cheerio");

//下载爬取的图片文件夹
let downloadDir = 'C:/Users/admin/Desktop/spider/';

/**
 * 开始爬取
 * @param url
 */
function start(url) {
    let result = [];
    https.get(url, (response) => {
        //获取响应数据
        response.on('data', (chunk) => {
            result.push(chunk);
        })
        //响应结束
        response.on('end', () => {
            //将数据转换为字符串(html字符串)
            let data = result.join('');
            spider(data)
        })
    })
}

/**
 * 爬虫函数
 * @param data 网页数据
 */
function spider(data) {
    let $ = cheerio.load(data);
    let items = $('.pli li');
    console.log('爬取到的数据条数:', items.length);
    items.each((index, item) => {
        let url = $(item).find('.il_img img').attr('src');
        url = url.split('!')?.[0];
        url = `https:${url}`
        let title = $(item).find('p a').text();
        let imgType = url.split('.').pop();
        request(url).pipe(fs.createWriteStream(`${downloadDir}/${title}_${index}.${imgType}`));
    });
}

//开始爬取
start('https://www.k2r2.com/shaonv_c43757/9.html');

启动以后就会将爬取到的图片下载到指定文件夹中

原网页的图片列表

爬取到的图片

相关推荐
小白要努力sgy19 分钟前
待学习--中间件
学习·中间件
~无忧花开~28 分钟前
CSS学习笔记(五):CSS媒体查询入门指南
开发语言·前端·css·学习·媒体
吴鹰飞侠44 分钟前
AJAX的学习
前端·学习·ajax
我的xiaodoujiao1 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 19--测试框架Pytest基础 3--前后置操作应用
python·学习·测试工具·pytest
lzj_pxxw1 小时前
嵌入式开发技巧:舍弃标志位,用宏定义函数实现程序单次运行
笔记·stm32·单片机·嵌入式硬件·学习
江苏世纪龙科技2 小时前
【世纪龙科技】新能源汽车动力电池拆装与检测虚拟实训软件介绍
学习
林希_Rachel_傻希希2 小时前
Express 入门全指南:从 0 搭建你的第一个 Node Web 服务器
前端·后端·node.js
whale fall2 小时前
与deepseek用英语聊天的第一天
学习
dxnb223 小时前
Datawhale25年10月组队学习:math for AI+Task3线性代数(下)
人工智能·学习·线性代数
Century_Dragon3 小时前
【世纪龙科技】新能源汽车动力电池拆装与检测虚拟实训软件介绍
学习