xhs-comment-analyzer
Инструмент анализа комментариев Xiaohongshu (XHS Comment Analyzer)
Инструмент для автоматического сбора и анализа UGC-комментариев на Xiaohongshu, ориентированный на команды бренд-маркетинга. Поддерживает поиск заметок по комбинации брендовых и категорийных слов, массовое извлечение комментариев (включая подкомментарии), трёхмерный анализ (ключевые слова / эмоции / популярность) и экспорт отчётов в форматах Excel+JSON. Работает в виде MCP-сервера, может вызываться напрямую AI-клиентами (TRAE / Claude / Cursor), а также поддерживает автономный запуск через CLI.
Ключевые возможности
Автоматический поиск заметок: поиск по комбинации брендовых и категорийных слов, автоматическая подгрузка прокруткой, интеллектуальная фильтрация нерелевантного контента.
Массовый сбор комментариев: последовательное открытие страниц деталей заметок, извлечение полной информации о родительских и дочерних комментариях, поддержка возобновления прерванного сбора.
Трёхмерный движок анализа: извлечение ключевых слов с помощью jieba+TF-IDF, классификация эмоций на основе словаря + правил, оценка популярности (взаимодействие × временное затухание).
Экспорт отчётов в двух форматах: отчёт Excel из 5 листов + структурированные данные JSON.
Интеграция с AI-рабочими процессами: MCP-сервер предоставляет 4 инструмента, поддерживает управление всем процессом на естественном языке.
Related MCP server: Xiaohongshu (RedBook) MCP Server
Быстрый старт
Установка
pip install -e .
playwright install chromiumЗапуск тестов
python -m pytest tests/ -vИспользование CLI
# 首次使用:检查登录状态(会打开浏览器,手动完成登录)
python run.py login
# 搜索并抓取评论(使用预设配置)
python run.py search
# 抓取单篇笔记评论
python run.py single "https://www.xiaohongshu.com/search_result/xxx?xsec_token=yyy"
# 对已有 JSON 重新分析
python run.py analyze data/output/report.jsonКонфигурация MCP
Добавьте в конфигурацию MCP в TRAE / Claude / Cursor:
{
"mcpServers": {
"xhs-comment-analyzer": {
"command": "python",
"args": ["-m", "src.mcp_server"],
"cwd": "/path/to/xhs-comment-analyzer-package"
}
}
}После настройки AI-клиент может вызывать на естественном языке: "Помоги найти комментарии о мелкой бытовой технике Bear Electric и сгенерировать аналитический отчёт".
Список инструментов MCP
Инструмент | Функция |
| Массовый поиск заметок по бренду+категории, сбор комментариев, анализ и экспорт |
| Сбор комментариев с одной заметки Xiaohongshu и их анализ |
| Повторный анализ ключевых слов/эмоций/популярности для уже собранного JSON-файла |
| Проверка статуса входа в Xiaohongshu |
Структура проекта
xhs-comment-analyzer-package/
├── src/ # 源代码
│ ├── scraper/ # 抓取层
│ │ ├── browser.py # Playwright 浏览器管理 (登录态持久化、反检测)
│ │ ├── comment_scraper.py # 评论抓取核心 (搜索/单篇/批量/断点续抓)
│ │ └── models.py # 数据模型 (7 个 Pydantic 模型)
│ ├── analyzer/ # 分析层
│ │ ├── keywords.py # 关键词提取 (jieba + TF-IDF)
│ │ ├── sentiment.py # 情感分类 (词典 + 规则)
│ │ └── heat.py # 热度评分 (互动量 × 时效衰减)
│ ├── exporter/
│ │ └── excel_exporter.py # 导出 Excel (5 Sheet) + JSON
│ └── mcp_server.py # MCP Server (4 个工具)
├── tests/ # 单元测试 (38 个用例)
├── data/
│ ├── cookies/ # 登录 cookie 持久化
│ ├── dictionaries/ # 自定义词典
│ │ ├── domain_words.txt # 领域词典 (69 个小家电术语)
│ │ ├── stopwords.txt # 停用词表
│ │ ├── positive_words.txt # 正面情感词
│ │ ├── negative_words.txt # 负面情感词
│ │ ├── negation_words.txt # 否定词
│ │ └── degree_adverbs.txt # 程度副词 (词<TAB>权重)
│ └── output/ # 导出文件 (Excel/JSON)
├── docs/ # 产品文档
│ └── xhs-product-doc.html # 完整产品文档 (PRD/架构/工作流/算法/接口)
├── run.py # CLI 入口 (login/search/single/analyze)
├── conftest.py # pytest 配置
├── pyproject.toml # 依赖管理
├── .gitignore
└── README.mdФормат вывода
Отчёт Excel (5 листов)
Лист | Содержание |
Детали комментариев | Все комментарии, отсортированные по популярности, включая заголовок заметки/URL/текст комментария/автора/время/лайки/ответы/эмоцию/популярность |
Аналитическое резюме | Количество собранных заметок, общее количество комментариев, комментарии, связанные с продуктом, статистика распределения эмоций |
Топ-10 ключевых слов | Высокочастотные ключевые слова и их доля |
Топ-10 горячих комментариев | 10 комментариев с наивысшим баллом популярности |
Сводка по заметкам | Количество лайков, комментариев и общий балл популярности для каждой заметки |
Отчёт JSON
Структурированные полные данные, включающие конфигурацию задачи, статистику сводки, список ключевых слов, полный список комментариев и пути к файлам, удобно для повторного использования программами.
Ключевые алгоритмы
Извлечение ключевых слов (jieba + TF-IDF)
Каждый комментарий рассматривается как отдельный документ. После сегментации jieba удаляются стоп-слова и односимвольные слова, вычисляется вес TF-IDF (сглаживание в стиле sklearn), возвращаются топ-10 ключевых слов и их доля. Встроенный словарь предметной области мелкой бытовой техники (69 терминов) предотвращает разбиение составных слов.
Анализ эмоций (словарь + правила)
Основан на словаре положительных/отрицательных эмоций + инверсия отрицаний (окно из 2 предшествующих слов, поддержка двойного отрицания) + взвешивание наречий степени ("очень" ×1.5, "особенно" ×2.0 и т.д.). Нормализация до диапазона [-1, 1], отображение на метки положительный/отрицательный/нейтральный.
Оценка популярности (взаимодействие × временное затухание)
base_score = like_count × 2 + reply_count × 3 + sub_comment_count × 1
time_decay = 0.95 ^ days_ago
heat_score = (base_score × time_decay / max_raw_heat) × 100Вес количества ответов самый высокий (3), так как ответы указывают на глубокое обсуждение; лайки — средний (2); дочерние комментарии — самый низкий (1). Затухание 5% в день, чтобы недавние высокоактивные комментарии были в приоритете.
Безопасность
Не обходит проверки: инструмент не вводит логин/пароль, не имитирует сканирование QR-кода, не обрабатывает капчу автоматически.
Приоритет ручного вмешательства: все операции входа и капчи выполняются человеком в видимом окне браузера.
Видимый браузер: всегда используется headless=False, пользователь может видеть и вмешиваться в любой момент.
Предупреждение о рисках: автоматическая остановка после 3 последовательных появлений капчи для предотвращения срабатывания защиты.
Возобновление с точки останова: поддержка прерывания и восстановления, прогресс сохраняется в
progress.json.Персистентность Cookie: состояние входа сохраняется в
xhs_cookies.json, избегая частого повторного входа.
Технологический стек
Зависимость | Назначение |
Python 3.12+ | Среда выполнения |
Playwright | Автоматизация браузера |
MCP SDK | Протокол MCP-сервера |
jieba | Сегментация китайского текста |
openpyxl | Экспорт Excel |
Pydantic | Валидация моделей данных |
Документация продукта
Полная интерактивная документация находится в docs/xhs-product-doc.html, открывается в браузере. Включает 9 разделов:
Обзор продукта
Документ требований к продукту (PRD)
Архитектура системы
Рабочий процесс
Ключевые алгоритмы
Безопасность и антидетект
Модели данных
Интерфейс MCP
Руководство пользователя
Пример данных
Каталог data/output/ содержит пример вывода реального запуска (категория мелкой бытовой техники Bear Electric), который можно использовать как справочный:
Количество заметок: 8 (после фильтрации)
Количество комментариев: 58 (включая дочерние)
Распределение эмоций: положительные 22.4%, отрицательные 10.3%, нейтральные 67.2%
Ключевые слова: Bear, нравится, пароварка
Конфигурация и переменные окружения
Инструмент по умолчанию не требует никаких переменных окружения или ключей для работы; все состояния входа выполняются человеком в видимом браузере, Cookie сохраняются в
data/cookies/.Если в дальнейшем потребуется подключение внешних сервисов (прокси, API-ключи и т.д.), поместите конфигурацию в файл
.env(игнорируется.gitignore) и используйте шаблон.env.example. Никогда не загружайте реальные ключи.Следующие каталоги/файлы исключены из
.gitignoreи не попадут в репозиторий:data/cookies/*.json(состояние входа),data/output/*(результаты сбора),data/progress.json,data/error.log,.envи т.д.
Описание каталогов и файлов
Путь | В репозитории? | Описание |
| ✅ | Весь исходный код |
| ✅ | Модульные тесты |
| ✅ | Словари эмоций/сегментации (текстовые) |
| ❌ (только | Cookie входа, конфиденциально |
| ❌ (только | Результаты сбора и анализа |
| ✅ | Документация продукта |
| ❌ | Конфиденциальные настройки |
Лицензия
Этот проект распространяется под лицензией MIT. Подробнее см. в файле LICENSE (если он не предоставлен, свяжитесь с автором).
Available Tools
4 toolsanalyze_commentsA
对已抓取的评论JSON文件重新进行关键词/情感/热度分析。
适用于需要用不同参数重新分析已有数据的场景。
Args: file_path: 已抓取的评论JSON文件路径
Returns: JSON 格式的分析结果
| Name | Required | Description | Default |
|---|---|---|---|
| file_path | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description must carry the full burden. It states the tool reads a JSON file and returns JSON analysis results, implying it is read-only and does not modify the original file. However, it does not disclose any potential side effects, required permissions, or error handling (e.g., missing file). The behavioral traits are partially transparent but lack depth.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise—three short sentences that cover the tool's purpose, usage scenario, and parameter. There is no wasted text, and the structure is front-loaded with the core action. Every sentence earns its place.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description claims re-analysis with 'different parameters' but only exposes the file_path parameter, suggesting the analysis parameters are embedded in the file or tool configuration—this is unclear. The return type is mentioned but not detailed. Given the tool's simplicity, the description is moderately complete but leaves ambiguity about how analysis parameters are controlled.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The only parameter 'file_path' has a description in the tool description ('path to scraped comment JSON file') that adds meaning beyond the schema's title 'File Path'. The schema coverage is 0%, so the description compensates well. It could be more specific (e.g., absolute path, supported formats), but it is sufficient for the single parameter.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool re-analyzes scraped comment JSON files for keyword, sentiment, and popularity. It distinguishes from sibling tools (run_search_task, scrape_single_note, check_login_status) which are for different tasks. However, the exact nature of 'analysis' is not fully specified, leaving some ambiguity.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly says it is suitable for re-analyzing existing data with different parameters. This provides clear context for when to use it. It does not mention exclusions or alternatives, but no sibling tool directly competes for this re-analysis purpose.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
check_login_statusA
检查小红书登录状态,返回是否需要人工登录。
如果未登录,会自动打开浏览器窗口供用户手动登录。
Returns: JSON 格式的登录状态信息
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It discloses the key side effect of automatically opening a browser window for manual login if not logged in. It also mentions the return format. However, it does not clarify whether the tool blocks until login completes or times out, which is a minor gap.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise with three short sentences plus a return line. Every sentence serves a clear purpose: stating the function, describing the automatic behavior, and indicating the output format. No wasted words.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool has no parameters and an output schema exists, the description adequately covers the core functionality and side effect. It could be improved by explicitly linking to sibling tools as a prerequisite, but overall it provides sufficient context for an agent to understand when and how to use it.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
There are zero parameters, so schema coverage is trivially 100%. The baseline is 4 per the rubric. The description does not add parameter-specific information but that is unnecessary. It provides context about the return value format, which is beneficial but not part of parameter semantics.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: checking Xiaohongshu login status and determining whether manual login is needed. It distinguishes itself from sibling tools like 'run_search_task' or 'scrape_single_note' by focusing on authentication rather than data operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies the tool should be used to verify login status before performing other tasks, and it explains the automated browser opening when not logged in. However, it does not explicitly state when to use this tool versus alternatives or mention prerequisites, leaving some implicit inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
run_search_taskA
搜索小红书笔记并批量抓取产品评论,返回分析结果和文件路径。
自动化流程: 搜索匹配笔记 → 逐篇抓取评论 → 关键词提取 + 情感分类 + 热度评分 → 导出 Excel + JSON
Args: brand_keywords: 品牌词列表 (必须匹配), 如 ["小熊"] category_keywords: 品类词列表 (必须匹配), 如 ["小家电"] product_keywords: 具体产品词列表 (可选), 如 ["酸奶机", "蒸蛋器"] max_notes: 最多抓取笔记数 (1-200), 默认20 max_comments_per_note: 每篇最多评论数 (1-1000), 默认100 sort_by: 排序方式, general=综合, popularity=热门, time=最新 min_likes: 笔记最低点赞门槛, 默认0 comment_filter: 是否过滤产品相关评论, 默认True
Returns: JSON 格式的分析结果摘要,包含统计信息、关键词、情感分布和导出文件路径
| Name | Required | Description | Default |
|---|---|---|---|
| sort_by | No | general | |
| max_notes | No | ||
| min_likes | No | ||
| brand_keywords | Yes | ||
| comment_filter | No | ||
| product_keywords | No | ||
| category_keywords | Yes | ||
| max_comments_per_note | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
描述公开了核心行为(搜索、抓取、分析、导出)和返回结果(JSON摘要和文件路径),但由于缺少annotation,其未说明是否需前置登录、文件写入的持久性/位置、速率限制或错误处理等副作用,整体透明度中等。
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
描述以功能概述开头,后跟一行自动化流程,再按列表形式列出参数,结构清晰。但参数描述较详细,可适当精简,整体无冗余,信息密度合理。
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
描述覆盖了核心操作和所有参数,但缺少对错误处理、前提条件(如登录状态)、输出模式的具体字段说明以及文件路径的显式描述,导致在复杂场景下代理可能无法完全预知调用后的完整结果。
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
输入模式description coverage为0%,描述完全补偿了参数的语义缺失。为所有8个参数提供了清晰的定义、可选范围(如max_notes 1-200)、默认值和必填/可选标记,使代理能准确理解每个参数的作用。
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
描述以“搜索小红书笔记并批量抓取产品评论”开头,明确说明了动词+资源,随后列出了详细的自动化流程(搜索、抓取、分析、导出),直接与兄弟工具(scrape_single_note)形成对比,清晰标识了工具的整体范围和输出。
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
描述详细说明了参数用法(必填和可选),隐含了端到端批量任务场景,但没有明确说明何时应避免使用此工具(例如,只需抓取单条笔记时使用scrape_single_note),缺少与兄弟工具的显式区分指南。
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
scrape_single_noteA
抓取单篇小红书笔记的评论并分析。
适用于已知笔记URL、只需抓取单篇评论的场景。
Args: note_url: 小红书笔记URL, 如 https://www.xiaohongshu.com/explore/xxxxx max_comments: 最多抓取评论数, 默认100
Returns: JSON 格式的评论列表和分析摘要
| Name | Required | Description | Default |
|---|---|---|---|
| note_url | Yes | ||
| max_comments | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions 'scrape and analyze' but does not describe key behaviors such as network requirements, rate limiting, authentication (e.g., login status), error handling (e.g., invalid URL, note not found), or what 'analyze' specifically does. Without these details, the agent may misuse the tool or encounter unexpected failures.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is extremely concise: two short sentences defining the purpose and context, followed by structured Args and Returns sections. Every sentence serves a clear function, and there is no redundancy. The format is easy to parse and front-loaded with the most critical information.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity (2 parameters, no annotations, has output schema), the description covers the essential purpose, parameters, and return format. However, it lacks important context about behavioral aspects (e.g., rate limits, login requirements, error scenarios) that would help an agent use it reliably. Completeness is adequate for straightforward use but not comprehensive.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has 0% description coverage, so the description is the sole source of parameter semantics. It provides meaning for both parameters: note_url is explained with an example URL, and max_comments is described as the maximum number of comments to scrape with a default of 100. This adds significant value beyond the schema's bare property titles. A slight deduction for not specifying format requirements (e.g., valid URL patterns) or edge-case behavior.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool's purpose: scraping and analyzing comments from a single Xiaohongshu note given a URL. It uses specific verbs ('抓取', '分析') and specifies the resource ('单篇小红书笔记的评论'). The sibling tools (run_search_task, analyze_comments, check_login_status) are distinct, and the description explicitly frames the use case as '已知笔记URL、只需抓取单篇评论的场景', which differentiates it from search or bulk tasks.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides a clear usage context: when you have a known note URL and only need to scrape comments from that single note. However, it does not explicitly state when not to use this tool (e.g., for batch scraping or analysis without scraping), nor does it mention alternatives like run_search_task for searching notes or analyze_comments for analyzing already scraped data. The guidance is implied rather than overt.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.1.0- First observed
analyze_comments - First observed
check_login_status - First observed
run_search_task - First observed
scrape_single_note
TDQS
Scored across 4 tools
Each tool targets a distinct phase of the workflow: run_search_task for full pipeline, scrape_single_note for single note scraping, analyze_comments for re-analysis, check_login_status for authentication. No overlap or ambiguity.
All tool names follow a consistent verb_noun pattern: run_search_task, scrape_single_note, analyze_comments, check_login_status. The verbs clearly indicate the action and nouns specify the target, making the naming predictable and clear.
With 4 tools, the set is tightly scoped to the server's purpose of comment analysis. Each tool serves a necessary and distinct role without excess. The count is appropriate for the domain.
The set covers the full workflow: login check, scraping (batch and single), and analysis. A minor gap is the lack of a dedicated tool for exporting or managing results beyond what the pipeline returns, but agents can work around this via file paths.
Maintenance
Related MCP Connectors
搜索笔记、浏览首页推荐、查看笔记内容与评论,并发表你的评论。直接在工作流中与小红书内容互动,高效跟进话题。
XHS search/details, PGY, comments/replies, users/ID resolution/posts, transcript
Search Xiaohongshu products by keyword.
Export public leads from Instagram, TikTok, Facebook, X and Google Maps through your AI assistant.
Related MCP Servers
- AlicenseBqualityFmaintenanceEnables users to search and retrieve content from Xiaohongshu (Red Book) platform with smart search capabilities and rich data extraction including note content, author information, and images.162 npm29MIT
- FlicenseNot gradedqualityDmaintenanceEnables automated interaction with Xiaohongshu (Little Red Book) platform including searching posts, retrieving content and comments, and posting AI-generated comments with persistent login support.454-
- FlicenseNot gradedqualityDmaintenanceEnables automated searching and commenting on Xiaohongshu with AI-generated comments via MCP clients like Claude, supporting login persistence, note analysis, and four comment types.-
- AlicenseNot gradedqualityDmaintenanceEnables automated interaction and data scraping for Xiaohongshu (RedNote), including posting, liking, commenting, following, and retrieving user and note data.5MIT