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);
                            }); 
相关推荐
专注VB编程开发20年2 小时前
Python爬虫、提取网页内容,免费调用谷歌翻译接口
爬虫·python·信息可视化
Data 实验室2 小时前
TaskPyro爬虫管理平台 v2.3.4:脚本即接口,调度即编排
爬虫
小白学大数据2 小时前
全站链接深度爬取:Python GUI 事件绑定 + 运行时动态过滤实现思路
开发语言·爬虫·python
绘梨衣54712 小时前
某爬虫策略的基础skills
爬虫·ai编程
郑洁文14 小时前
基于网络爬虫的Web敏感信息泄露自动化检测工具
前端·爬虫·网络安全·自动化
上海云盾-小余21 小时前
爬虫与 CC 同源伪装甄别:基于访问行为的拦截落地方案
爬虫
如烟花的信页1 天前
数美滑块逆向分析
javascript·爬虫·python·js逆向
Wonderful U1 天前
基于Python爬虫+Django的轻量化天气预报系统:从数据抓取到可视化展示的完整实战
爬虫·python·django
兆。1 天前
LangChain自动化工具集成指南:面向爬虫开发者
爬虫·langchain·自动化
深蓝电商API1 天前
当爬虫遇见大模型:AI驱动的智能数据采集新范式
人工智能·爬虫