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);
                            }); 
相关推荐
elderingezez1 小时前
2024年用scrapy爬取BOSS直聘的操作
爬虫·python·scrapy
nice肥牛1 小时前
Python爬取国家医保平台公开数据
开发语言·爬虫·python·国家医保平台
吾名招财3 小时前
四、(2)获取数据(补充urllib)(爬虫及数据可视化)
爬虫·python
夏日恋雨6 小时前
如何使用python网络爬虫批量获取公共资源数据教程?
爬虫·python·大气科学·生态学·环境科学·文本分析·公共资源
IT数据小能手15 小时前
如何利用React和Python构建强大的网络爬虫应用
爬虫·python·react.js
小白学大数据1 天前
Python爬虫与数据可视化:构建完整的数据采集与分析流程
开发语言·爬虫·python·信息可视化
IT数据小能手1 天前
使用 PHP 和 Selenium WebDriver 实现爬虫
爬虫·selenium·php
萌新杰少1 天前
【豆包Marscode体验官】爽了!直接口诉让豆包开发文章评论区BOT!
爬虫·aigc·coze
IT数据小能手1 天前
PHP多线程爬虫:高效解析电商网页内容
开发语言·爬虫·php
励志的大鹰哥1 天前
JS爬虫实战之Fastmoss
javascript·爬虫