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);
                            }); 
相关推荐
SEO_juper1 小时前
Java 并发编程实战:从线程基础到高并发架构
运维·人工智能·爬虫·chatgpt·seo
大数据魔法师7 小时前
curl_cffi从入门到实战
爬虫·python
2601_960102049 小时前
2026新破甲AI站群泛程序
爬虫·搜索引擎·蜘蛛池
深蓝电商API12 小时前
AI 如何辅助编写爬虫?
爬虫
狗都不学爬虫_12 小时前
AI逆向 - 天御无感点击验证(补+纯)
爬虫·python·网络爬虫
小静AI工程实验室13 小时前
Python 爬虫翻页为何重复、漏数据?SQLite 复现 OFFSET、复合游标与快照的 8 项检查
爬虫·python·sqlite
码农学院14 小时前
制造业B2B官网GEO实战:用 Python 向量相似度给老产品手册自动补语义内链,让 AI 爬虫抓得更深
运维·人工智能·爬虫·ai优化aio
电商API_1800790524714 小时前
电商平台数据分析实战_帖子
开发语言·爬虫·python·数据采集·京东
码农学院1 天前
企业官网改版GEO实战:把 Blazor SPA 改造成 AI 爬虫可读的预渲染方案
人工智能·爬虫·geo
张小凡vip2 天前
python--爬虫--经验积累的遇到的坑
开发语言·爬虫·python