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);
                            }); 
相关推荐
喵手8 小时前
Python爬虫实战:手把手教你Python 自动化构建志愿服务岗位结构化数据库!
爬虫·python·自动化·数据采集·爬虫实战·零基础python爬虫教学·志愿服务岗位结构数据库打造
小邓睡不饱耶8 小时前
Python多线程爬虫实战:爬取论坛帖子及评论
开发语言·爬虫·python
喵手8 小时前
Python爬虫实战:手把手教你如何采集开源字体仓库目录页(Google Fonts / 其他公开字体目录)!
爬虫·python·自动化·数据采集·爬虫实战·零基础python爬虫教学·开源字体仓库目录页采集
axinawang9 小时前
正则表达式
爬虫·python
喵手10 小时前
Python爬虫实战:手把手带你打造私人前端资产库 - Python 自动化抓取开源 SVG 图标全目录!
爬虫·python·自动化·爬虫实战·零基础python爬虫教学·前端资产库打造·采集svg图标目录
WeeJot嵌入式1 天前
爬虫对抗:ZLibrary反爬机制实战分析
爬虫·python·网络安全·playwright·反爬机制
进击的雷神1 天前
攻克JSON嵌套HTML的双重解析难题:基于多层数据提取的精准爬虫设计
爬虫·html·json·spiderflow
前端小趴菜~时倾1 天前
自我提升-python爬虫学习:day05-函数与面向对象编程
爬虫·python·学习
进击的雷神1 天前
攻克JSON接口分页与对象数组处理:基于AJAX数据源的精准博客爬虫设计
爬虫·ajax·json·spiderflow
vx_biyesheji00011 天前
计算机毕业设计:Python汽车数据分析系统 Django框架 requests爬虫 可视化 车辆 数据分析 大数据 机器学习(建议收藏)✅
爬虫·python·算法·机器学习·django·汽车·课程设计