目录

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);
                            }); 
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
小军要奋进9 小时前
httpx模块的使用
笔记·爬虫·python·学习·httpx
K哥爬虫1 天前
【APP 逆向百例】淘某热点 APP 逆向分析
爬虫
那年那棵树1 天前
【爬虫】网易云音乐评论数据爬取
javascript·爬虫·python
那年那棵树1 天前
【爬虫】携程旅游项目数据爬取
爬虫·python·旅游
猿小猴子1 天前
使用Scrapy官方开发的爬虫部署、运行、管理工具:Scrapyd
爬虫·scrapy
九筠1 天前
python网络爬虫开发实战之Ajax数据提取
前端·爬虫·ajax·网络爬虫
最强菜鸟2 天前
python爬虫爬取淘宝热销(热门)零食商品加数据清洗、销量、店铺及词云数据分析_源码及相关说明文档;售后可私博主
爬虫·python·数据分析
eqwaak02 天前
DrissionPage高级技巧:从爬虫到自动化测试
人工智能·爬虫·python·语言模型·自然语言处理·drissionpage
fc&&fl2 天前
AI爬虫?爬!
人工智能·爬虫·python
deckcode3 天前
xpath定位
爬虫·功能测试·网络爬虫·web测试