小红书关键词爬虫

标题

  • [1 统计要收集的关键词,制作一个文件夹](#1 统计要收集的关键词,制作一个文件夹)
  • [2 爬取每一页的内容](#2 爬取每一页的内容)
  • [3 爬取标题和内容](#3 爬取标题和内容)
  • [4 如果内容可以被查看,爬取评论内容](#4 如果内容可以被查看,爬取评论内容)
  • [5 将结果进行汇总,并且每个帖子保存为一个json文件,具体内容](#5 将结果进行汇总,并且每个帖子保存为一个json文件,具体内容)
  • [6 总结](#6 总结)

1 统计要收集的关键词,制作一个文件夹

例如,我要收集旅游相关的,就收集:

旅游、旅行、旅游攻略,这些词,做成一个txt文件。

用一个浏览器登录上小红书账号,然后记录写cookies,例如:

2 爬取每一页的内容

主要使用request,js模块,将爬取的内容保存为res,里面包含一页20条数据。

python 复制代码
info = re.sub(r'"page":".*?"', f'"page":"{page}"', info)
        ret = js.call('get_xs', api, info, cookies["a1"])
        headers['x-s'], headers['x-t'] = ret['X-s'], str(ret['X-t'])
        response = requests.post(search_url, headers=headers, cookies=cookies, data=info.encode('utf-8'))
        res = response.json()

3 爬取标题和内容

从每一个note里面解析出标题,内容等信息。

python 复制代码
result = {}
    result["title"] = data['note_card']['title']
    result["desc"] = data['note_card']['desc'].replace("\n", "").replace("\t", "")
    tags_temp = data['note_card']['tag_list']
    tags = []
    for tag in tags_temp:
        try:
            tags.append(tag['name'])
        except:
            pass
    result["tags"] = tags
    result["time"] = timestamp_to_str(data['note_card']['time'])

4 如果内容可以被查看,爬取评论内容

每个帖子里面的评论的单独的url,需要根据id号进行拼接,所以根据第3节获取的user-id,进行拼接,然后再用get进行访问,最后获得每条评论,注意有些帖子是不能被查看的,所以需要进行判断。

python 复制代码
note_id = url.split('/')[-1]
    comments_url = "https://edith.xiaohongshu.com/api/sns/web/v2/comment/page?note_id={}&image_scenes=FD_WM_WEBP,CRD_WM_WEBP".format(
        note_id)
    response = requests.get(comments_url, headers=headers, cookies=cookies)
    res = response.json()
    comments = []
    for line in res["data"]["comments"]:
        comment_str = line["content"]
        comments.append(comment_str)

5 将结果进行汇总,并且每个帖子保存为一个json文件,具体内容

包含:标题,具体内容,标题,创建时间,评论内容。每个关键词一个文件夹。

6 总结

详细代码私聊,注意本内容没有爬取图片,如果需要可以添加。

相关推荐
心疼你的一切1 天前
【矛与盾的博弈:ZLibrary反爬机制实战分析与绕过技术全解析】
人工智能·爬虫·python·网络爬虫
axinawang1 天前
XPath与lxml解析库
爬虫·python
FPGA的花路1 天前
Windows10/11永久关闭自动更新
windows·自动更新·永久关闭
水饺编程1 天前
第4章,[标签 Win32] :SysMets3 程序讲解01
c语言·c++·windows·visual studio
私人珍藏库1 天前
[Windows] Cap 0.4.81
windows·工具·录屏·软件·多功能
想你依然心痛1 天前
从零开始:Mac/Windows/Linux 三系统开发环境配置完全指南
linux·windows·macos
亿牛云爬虫专家1 天前
爬虫踩坑实录:OkHttp 接入爬虫代理报 Too many tunnel connections attempted 深度解析
爬虫·okhttp·https·爬虫代理·connect·隧道代理·ip 切换
ths5121 天前
doris 中 array_agg函数用法总结
windows
de_wizard1 天前
DeepSeek API 调用 - Spring Boot 实现
windows·spring boot·后端
小学鸡!1 天前
win10/win11下载安装Docker,Windows安装Docker Desktop 【保姆级教程】
windows·docker·容器