小红书关键词爬虫

标题

  • [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 总结

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

相关推荐
wuyk55513 小时前
Spider-第10讲-SQLite持久化与去重
数据库·爬虫·sqlite
Funlang14 小时前
在 Windows 95 上跑 Fun
windows
ö Constancy19 小时前
一台电脑的硬件组成与作用:按功能分类详解(Windows 与 Linux 视角)
linux·windows·电脑
wuyk55519 小时前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
wuyk5552 天前
Spider-第07讲-JSON接口与正则提取
爬虫·python·json
feasibility.2 天前
一物降一物?AI逆向没有终局:REA拆App,BLA设套,LASIK清场
人工智能·爬虫·github·逆向·skill·rea
雪落漂泊2 天前
Liunux进程(七):程序控制篇(中)
linux·运维·windows
承渊政道2 天前
Fooocus本地AI绘图教程:Windows部署、低门槛生图与远程访问
人工智能·windows·cpolar·fooocus·生图
陈工大模型3 天前
收到乱码压缩包之后,我重新测了 7-Zip、Bandizip 和win解压缩
windows·电脑·软件工程·软件需求·7-zip
谙弆悕博士3 天前
在文件夹右键直接打开 Kali WSL:一条 `wsl --cd` 注册表脚本
windows·脚本·wsl·右击·ksli