nodejs爬虫小红书评论区

发现好像还是爬虫的知识热度比较高,最近一直在加强JS这块。这两天脚本模拟爬BOSS的时候也想着怎么用nodejs,昨天都没更新文章,Q-Q,因为一直failed没啥成果。

使用模块

这边可以看到使用的模块其实也挺多,但主要还是http和https模块,这两个用来爬取信息算是比较方便的

javascript 复制代码
var http=require('http');
var https=require('https');
var _=require('lodash')
const { createObjectCsvWriter } = require('csv-writer');
const download=require('download')
javascript 复制代码
const csvWriter = createObjectCsvWriter({
    path: 'comments.csv',
    header: [
        { id: 'comment_id', title: 'Comment ID' },
        { id: 'user_id', title: 'User ID' },
        { id: 'content', title: 'Content' },
        { id: 'url', title: 'url' },
        // { id: 'parent_id', title: 'Parent Comment ID' }  // 添加父评论
    ]
});

先是生成了一个csv文件用于存储到时候爬取到的信息

javascript 复制代码
    const options = {
        hostname: 'edith.xiaohongshu.com',
        port: 443,
        path: '/api/sns/web/v2/comment/page?note_id=6663171e000000000d00f19c&cursor=&top_comment_id=&image_formats=jpg,webp,avif',
        method: 'GET',
        headers: {
            'Cookie':'你的cookie',
            'User-Agent': 'User-Agent'  // 可选: 设置User-Agent
        }
    };

这边主要就是http请求的信息设定了,headers信息直接复制就好了

调用HTTPS请求并将结果存放到data

javascript 复制代码
    https.get(options2,(resp)=>{
         let data=''
         resp.on("data",(chunk)=>{
            data+=chunk;
        });
        resp.on('end',()=>{

得到的data会是很长的内容,需要用正则表达式将数据分割出来

javascript 复制代码
        resp.on('end',()=>{
            // <script[^>]*>\s*window\.__INITIAL_STATE__\s*=\s*(\{[\s\S]*?\})
            const scriptRegex = /{"id":"([^"]+)",("modelType":"[^"]+")/g;
            let match;
            
            while ((match = scriptRegex.exec(data)) !== null) {
                if (match[1]) {
                    const initialState = match[1];

再将需要的数据存放到csv文件中

javascript 复制代码
                            csvWriter.writeRecords(records, { append: true })
                            .then(() => {
                                console.log('The CSV file was written successfully');
                            })
                            .catch(err => {
                                console.error('Error writing CSV file:', err);
                            }); 
相关推荐
B站计算机毕业设计超人4 分钟前
计算机毕业设计Hadoop+Spark+DeepSeek-R1大模型民宿推荐系统 hive民宿可视化 民宿爬虫 大数据毕业设计(源码+LW文档+PPT+讲解)
大数据·hadoop·爬虫·机器学习·课程设计·数据可视化·推荐算法
风123456789~21 分钟前
【爬虫基础】第一部分 网络通讯-编程 P3/3
网络·爬虫
奔跑吧邓邓子1 小时前
【Python爬虫(44)】分布式爬虫:筑牢安全防线,守护数据之旅
开发语言·分布式·爬虫·python·安全
奔跑吧邓邓子2 小时前
【Python爬虫(45)】Python爬虫新境界:分布式与大数据框架的融合之旅
开发语言·分布式·爬虫·python·大数据框架
奔跑吧邓邓子13 小时前
【Python爬虫(36)】深挖多进程爬虫性能优化:从通信到负载均衡
开发语言·爬虫·python·性能优化·负载均衡·多进程
奔跑吧邓邓子17 小时前
【Python爬虫(27)】探索数据可视化的魔法世界
开发语言·爬虫·python·数据可视化
Java开发-楠木18 小时前
爬虫破解网页禁止F12
爬虫
数据小爬虫@1 天前
爬虫获取的数据能用于哪些数据分析?
爬虫·数据挖掘·数据分析
笨鸟笃行1 天前
爬虫第七篇数据爬取及解析
开发语言·爬虫·python
Jelena157795857921 天前
使用Java爬虫获取1688 item_get_company 接口的公司档案信息
java·开发语言·爬虫