⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

version unknown

xiaohongshu-skill

deliciousbuding@deliciousbuding⭐ 43 stars· last commit 2mo ago· 1 open issues

小红书 / Xiaohongshu / RedNote AI Agent Skill。用 Python Playwright 搜索和读取内容、管理登录会话、发布图文/视频/长文、评论、点赞和收藏;默认输出 JSON,任何写操作都必须先获得用户确认。用户提到 xiaohongshu、小红书、rednote、小红书搜索、发到小红书、小红书笔记分析、小红书运营或小红书自动化时触发。

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 43 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

xiaohongshu-skill

CI Release Python License

面向 AI Agent 和命令行用户的小红书浏览器工具箱。它通过 Python Playwright 提供搜索、详情读取、推荐流、登录、发布、评论、点赞、收藏、模板、策略和 SOP 能力。

  • CLI 默认输出 JSON,适合 Agent 和自动化工具消费。
  • 多账号通过 profile 隔离浏览器会话和本地状态。
  • 发布结果区分已确认、已提交但未确认、失败,避免把按钮点击当成发布成功。
  • 默认测试不访问小红书;真实浏览器测试需要显式开启。

本项目会操作真实账号。发布、评论、回复、点赞和收藏前必须获得用户明确确认。遇到验证码或安全验证时停止自动操作并切换到人工处理。

English documentation: README_EN.md

能力

类别命令写入账号
登录与账号qrcode, check-login, profiles, logoutlogout 会清除本地状态
内容发现search, feed, user, me, explore否
内容发布publish, publish-video, publish-md, publish-longform是
互动comment, reply, reply-notification, like, collect, unlike, uncollect是
内容工具template, strategy-*, sopSOP 取决于具体动作
开发辅助selectors, contracts否

完整参数见 CLI 命令参考。

安装

ClawHub

clawhub install xiaohongshu-skill

Agent Skills CLI

npx skills add DeliciousBuding/xiaohongshu-skill

本地可复现环境

git clone https://github.com/DeliciousBuding/xiaohongshu-skill.git
cd xiaohongshu-skill
uv sync --frozen --no-dev
uv run playwright install chromium

开发环境:

uv sync --frozen --group dev
uv run python -m scripts.quality check

全局 CLI

pip install git+https://github.com/DeliciousBuding/xiaohongshu-skill.git
playwright install chromium
xiaohongshu-skill --help

Docker

docker compose build
docker compose run --rm xiaohongshu qrcode --headless=false

更完整的系统和平台说明见 安装指南。

快速开始

1. 登录

uv run python -m scripts qrcode --headless=false
uv run python -m scripts check-login

2. 搜索和读取

uv run python -m scripts search "咖啡" --limit=5
uv run python -m scripts feed <feed_id> <xsec_token>
uv run python -m scripts user <user_id> <xsec_token>
uv run python -m scripts explore --limit=10

feed_id、user_id 和 xsec_token 应来自当前会话的搜索或详情结果,不要长期缓存安全参数。

3. 准备发布

默认发布命令只填写内容并停在发布页:

uv run python -m scripts publish \
  --title="周末咖啡记录" \
  --content="正文内容" \
  --images="/path/to/1.jpg,/path/to/2.jpg"

确认标题、正文、媒体、账号和可见范围后,才使用:

uv run python -m scripts publish ... --auto-publish

自动提交结果状态:

状态含义建议动作
confirmed观察到可信成功信号可以记录为成功
submitted_unconfirmed已点击提交,但没有观察到成功信号人工复核,禁止自动重试
failed未提交或观察到失败信号检查错误后再决定
ready内容已填写,尚未点击发布人工检查后决定是否提交

4. 多账号

uv run python -m scripts --profile brand-a qrcode --headless=false
uv run python -m scripts --profile brand-a search "咖啡"
uv run python -m scripts profiles

不同 profile 使用独立的浏览器数据、Cookie 备份和会话元数据。XHS_FP_SEED 可临时覆盖当前进程的稳定指纹 seed。

安全和限制

  • 不要关闭内置导航间隔和互动冷却。
  • 不要运行高频批量抓取或批量互动。
  • 遇到验证码、登录页或安全验证页时停止。
  • 不要在 issue、日志或截图中提交账号信息、Cookie、完整安全参数或二维码。
  • Docker 镜像以非 root 用户运行,本地敏感状态不会进入构建上下文。
  • XHS_ALLOW_NO_SANDBOX=true 只适用于明确需要关闭 Chromium sandbox 的隔离环境。

详见 安全说明。

工程设计

默认质量门:

uv run python -m scripts.quality check

CI 还会测试 Python 3.10、3.11、3.12,构建 wheel 和源码包,并验证 Docker 镜像。

来源与许可证

仓库原创代码按 Apache License 2.0 发布。部分浏览器行为参考或改写自 Apache-2.0 项目 xpzouying/xiaohongshu-mcp,详情见 第三方声明。

本项目与小红书官方无隶属或授权关系。使用者应自行遵守适用的平台规则、法律法规和账号安全要求。

// HOW IT'S BUILT

// FILES

103 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md3.6 KBf29cb66946c3upstream ↗
    ---
    name: xiaohongshu-skill
    description: 小红书 / Xiaohongshu / RedNote AI Agent Skill。用 Python Playwright 搜索和读取内容、管理登录会话、发布图文/视频/长文、评论、点赞和收藏;默认输出 JSON,任何写操作都必须先获得用户确认。用户提到 xiaohongshu、小红书、rednote、小红书搜索、发到小红书、小红书笔记分析、小红书运营或小红书自动化时触发。
    license: Apache-2.0
    compatibility: Requires Python 3.10 or newer and Playwright Chromium. Supports Windows, macOS, and Linux.
    metadata:
      openclaw:
        emoji: "📕"
        requires:
          anyBins:
            - python3
            - python
        os:
          - win32
          - linux
          - darwin
    ---
    
    # 小红书 Skill
    
    通过 JSON CLI 操作小红书浏览器会话。执行入口统一为:
    
    ```bash
    cd {baseDir}
    uv run python -m scripts <command>
    ```
    
    ## 安全规则
    
    发布、评论、回复、点赞、收藏、取消点赞和取消收藏会改变真实账号状态。执行前必须:
    
    1. 展示目标账号、内容、媒体和操作类型。
    2. 获得用户明确确认。
    3. 只执行用户确认的单次操作。
    
    遇到验证码、登录页或安全验证页时停止。不要自动绕过验证,不要运行批量抓取或批量互动。
    
    ## 任务路由
    
    | 用户目标 | 命令或参考 |
    | --- | --- |
    | 首次登录或重新登录 | `qrcode --headless=false` |
    | 检查登录 | `check-login` |
    | 管理多个账号 | `--profile <name>`;详见 `docs/INSTALL.md` |
    | 搜索笔记 | `search` |
    | 读取笔记详情 | `feed` |
    | 读取用户主页 | `user` 或 `me` |
    | 获取推荐流 | `explore` |
    | 准备或发布图文 | `publish` |
    | 准备或发布视频 | `publish-video` |
    | Markdown 转图片发布 | `publish-md` |
    | 准备或发布长文 | `publish-longform` |
    | 评论和回复 | `comment`、`reply`、`reply-notification` |
    | 点赞和收藏 | `like`、`collect`、`unlike`、`uncollect` |
    | 模板、策略和 SOP | `template`、`strategy-*`、`sop` |
    | 查看参数 | `python -m scripts <command> --help` |
    
    完整命令见 `docs/API.md`;安装和平台接入见 `docs/INSTALL.md`、`docs/INTEGRATIONS.md`。
    
    ## 初始化
    
    ```bash
    cd {baseDir}
    uv sync --frozen --no-dev
    uv run playwright install chromium
    uv run python -m scripts qrcode --headless=false
    ```
    
    开发者使用:
    
    ```bash
    uv sync --frozen --group dev
    uv run python -m scripts.quality check
    ```
    
    ## 只读示例
    
    ```bash
    uv run python -m scripts search "咖啡" --limit=5
    uv run python -m scripts feed <feed_id> <xsec_token>
    uv run python -m scripts explore --limit=10
    ```
    
    `feed_id`、`user_id` 和 `xsec_token` 必须来自当前会话的结果,不要长期缓存。
    
    ## 发布语义
    
    发布命令默认填写表单并返回 `ready`。用户确认后才能追加 `--auto-publish`。
    
    自动提交可能返回:
    
    - `confirmed`:已观察到可信成功信号。
    - `submitted_unconfirmed`:已点击提交但未确认成功;必须人工复核,禁止自动重试。
    - `failed`:提交失败或出现登录、验证码、安全验证等失败信号。
    
    ## 输出和错误
    
    标准输出是 JSON;诊断信息写入标准错误。Agent 应先读取 `status`,再依据 `scripts/output_contracts.py` 中的契约处理字段。
    
    发生 `captcha_required` 或浏览器安全验证时,不要重试循环。切换到有头模式并由用户处理。
    
    ## 本地状态
    
    每个 profile 独立保存浏览器状态、Cookie 备份和会话元数据。不要读取、展示、提交或外发这些文件。`XHS_FP_SEED` 只用于显式覆盖当前进程的稳定指纹 seed。
    
    安全和隐私规则见 `docs/SECURITY.md`。架构说明见 `docs/ARCHITECTURE.md`。
    
  • examples/claude-code/README.md1.3 KBfdc27630a233upstream ↗
    # Claude Code 集成
    
    xiaohongshu-skill 是一个 Claude Code Skill,Claude 会自动加载 `SKILL.md` 来理解如何使用。
    
    ## 怎么用
    
    ### 1. 克隆 + 装依赖
    
    ```bash
    git clone https://github.com/DeliciousBuding/xiaohongshu-skill.git
    cd xiaohongshu-skill
    uv sync --frozen --no-dev
    uv run playwright install chromium
    playwright install chromium
    ```
    
    ### 2. 加到 Claude Code
    
    在 Claude Code 的 Skills 目录加个 symlink:
    
    ```bash
    # Windows
    mklink /D %USERPROFILE%\.claude\skills\xiaohongshu-skill D:\path\to\xiaohongshu-skill
    
    # macOS / Linux
    ln -s /path/to/xiaohongshu-skill ~/.claude/skills/xiaohongshu-skill
    ```
    
    或者直接克隆到 skills 目录:
    
    ```bash
    git clone https://github.com/DeliciousBuding/xiaohongshu-skill.git ~/.claude/skills/xiaohongshu-skill
    ```
    
    ### 3. 扫码登录
    
    ```bash
    python -m scripts qrcode --headless=false
    ```
    
    扫完码 Cookie 自动保存在 `~/.xiaohongshu/`,以后不用再登。
    
    ### 4. 试试
    
    在 Claude Code 里说:
    
    - "帮我搜下小红书 北京美食"
    - "看看小红书上这个帖子怎么样"(给链接)
    - "把这个发到小红书"
    
    Claude 会自动跑对应命令。
    
    ## 不想装全局?
    
    用 Docker:
    
    ```bash
    docker compose run --rm xiaohongshu qrcode --headless=false
    docker compose run --rm xiaohongshu search "北京美食" --limit=5
    ```
    
  • examples/cursor/README.md791 B6773ef7a1345upstream ↗
    # Cursor Example
    
    Use this project as a local Skill folder or call the CLI from Cursor's agent shell.
    
    ## Local Setup
    
    ```bash
    git clone https://github.com/DeliciousBuding/xiaohongshu-skill.git
    cd xiaohongshu-skill
    uv sync --frozen --no-dev
    uv run playwright install chromium
    playwright install chromium
    python -m scripts qrcode --headless=false
    ```
    
    ## Shell Checks
    
    ```bash
    python -m scripts check-login
    python -m scripts search "上海咖啡" --limit=3
    python -m scripts contracts --command=search
    ```
    
    ## Prompt
    
    ```text
    Use the xiaohongshu-skill CLI in this repository. Search Xiaohongshu for "上海咖啡", return 3 JSON results, and do not run write commands.
    ```
    
    Write commands such as `publish`, `comment`, `like`, and `collect` need user confirmation before the agent runs them.
    
  • examples/n8n/README.md660 B28ddd4135b99upstream ↗
    # n8n Example
    
    Use an Execute Command node for read-only commands, then parse the JSON in a Code node.
    
    ## Search Command
    
    ```bash
    python -m scripts search "北京周末去哪" --limit=5
    ```
    
    Expected shape:
    
    ```json
    {
      "count": 5,
      "results": []
    }
    ```
    
    ## Safe Workflow
    
    1. Execute Command: run a read-only command such as `search`, `feed`, or `user`.
    2. Code: parse JSON and choose the fields your workflow needs.
    3. Manual approval: require a person before any write command.
    4. Execute Command: run `publish`, `comment`, `reply`, `like`, or `collect` only after approval.
    
    Keep account cookies and local profile data outside exported n8n workflow files.
    
  • examples/openclaw/README.md625 Bfdc8c44d57e3upstream ↗
    # OpenClaw Example
    
    Install through ClawHub when available:
    
    ```bash
    clawhub install xiaohongshu-skill
    ```
    
    Manual install:
    
    ```bash
    git clone https://github.com/DeliciousBuding/xiaohongshu-skill.git ~/.openclaw/skills/xiaohongshu-skill
    cd ~/.openclaw/skills/xiaohongshu-skill
    uv sync --frozen --no-dev
    uv run playwright install chromium
    playwright install chromium
    python -m scripts qrcode --headless=false
    ```
    
    Try:
    
    ```text
    帮我搜小红书上的深圳徒步攻略,返回 5 条,只要 JSON 摘要。
    ```
    
    OpenClaw should read `SKILL.md` and call `python -m scripts`. Any write command needs user confirmation first.
    
  • examples/README.md460 B154fcfeb8bd9upstream ↗
    # 集成示例
    
    本目录包含 xiaohongshu-skill 在不同平台/场景下的集成配置示例。
    
    | 目录 | 说明 |
    |------|------|
    | `claude-code/` | Claude Code MCP 集成配置 |
    | `cursor/` | Cursor agent shell 示例 |
    | `demo/` | 公开展示用合成 JSON,不含真实账号数据 |
    | `n8n/` | n8n Execute Command 节点示例 |
    | `openclaw/` | OpenClaw 和 ClawHub 安装示例 |
    
    更多集成方式(Docker、系统服务等)欢迎贡献。
    
  • README.md5.5 KBb09e76759aa9upstream ↗
    # xiaohongshu-skill
    
    [![CI](https://github.com/DeliciousBuding/xiaohongshu-skill/actions/workflows/ci.yml/badge.svg)](https://github.com/DeliciousBuding/xiaohongshu-skill/actions/workflows/ci.yml)
    [![Release](https://img.shields.io/github/v/release/DeliciousBuding/xiaohongshu-skill)](https://github.com/DeliciousBuding/xiaohongshu-skill/releases)
    [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue)](https://www.python.org/)
    [![License](https://img.shields.io/badge/license-Apache_2.0-blue)](LICENSE)
    
    面向 AI Agent 和命令行用户的小红书浏览器工具箱。它通过 Python Playwright 提供搜索、详情读取、推荐流、登录、发布、评论、点赞、收藏、模板、策略和 SOP 能力。
    
    - CLI 默认输出 JSON,适合 Agent 和自动化工具消费。
    - 多账号通过 profile 隔离浏览器会话和本地状态。
    - 发布结果区分已确认、已提交但未确认、失败,避免把按钮点击当成发布成功。
    - 默认测试不访问小红书;真实浏览器测试需要显式开启。
    
    > 本项目会操作真实账号。发布、评论、回复、点赞和收藏前必须获得用户明确确认。遇到验证码或安全验证时停止自动操作并切换到人工处理。
    
    English documentation: [README_EN.md](README_EN.md)
    
    ## 能力
    
    | 类别 | 命令 | 写入账号 |
    | --- | --- | --- |
    | 登录与账号 | `qrcode`, `check-login`, `profiles`, `logout` | `logout` 会清除本地状态 |
    | 内容发现 | `search`, `feed`, `user`, `me`, `explore` | 否 |
    | 内容发布 | `publish`, `publish-video`, `publish-md`, `publish-longform` | 是 |
    | 互动 | `comment`, `reply`, `reply-notification`, `like`, `collect`, `unlike`, `uncollect` | 是 |
    | 内容工具 | `template`, `strategy-*`, `sop` | SOP 取决于具体动作 |
    | 开发辅助 | `selectors`, `contracts` | 否 |
    
    完整参数见 [CLI 命令参考](docs/API.md)。
    
    ## 安装
    
    ### ClawHub
    
    ```bash
    clawhub install xiaohongshu-skill
    ```
    
    ### Agent Skills CLI
    
    ```bash
    npx skills add DeliciousBuding/xiaohongshu-skill
    ```
    
    ### 本地可复现环境
    
    ```bash
    git clone https://github.com/DeliciousBuding/xiaohongshu-skill.git
    cd xiaohongshu-skill
    uv sync --frozen --no-dev
    uv run playwright install chromium
    ```
    
    开发环境:
    
    ```bash
    uv sync --frozen --group dev
    uv run python -m scripts.quality check
    ```
    
    ### 全局 CLI
    
    ```bash
    pip install git+https://github.com/DeliciousBuding/xiaohongshu-skill.git
    playwright install chromium
    xiaohongshu-skill --help
    ```
    
    ### Docker
    
    ```bash
    docker compose build
    docker compose run --rm xiaohongshu qrcode --headless=false
    ```
    
    更完整的系统和平台说明见 [安装指南](docs/INSTALL.md)。
    
    ## 快速开始
    
    ### 1. 登录
    
    ```bash
    uv run python -m scripts qrcode --headless=false
    uv run python -m scripts check-login
    ```
    
    ### 2. 搜索和读取
    
    ```bash
    uv run python -m scripts search "咖啡" --limit=5
    uv run python -m scripts feed <feed_id> <xsec_token>
    uv run python -m scripts user <user_id> <xsec_token>
    uv run python -m scripts explore --limit=10
    ```
    
    `feed_id`、`user_id` 和 `xsec_token` 应来自当前会话的搜索或详情结果,不要长期缓存安全参数。
    
    ### 3. 准备发布
    
    默认发布命令只填写内容并停在发布页:
    
    ```bash
    uv run python -m scripts publish \
      --title="周末咖啡记录" \
      --content="正文内容" \
      --images="/path/to/1.jpg,/path/to/2.jpg"
    ```
    
    确认标题、正文、媒体、账号和可见范围后,才使用:
    
    ```bash
    uv run python -m scripts publish ... --auto-publish
    ```
    
    自动提交结果状态:
    
    | 状态 | 含义 | 建议动作 |
    | --- | --- | --- |
    | `confirmed` | 观察到可信成功信号 | 可以记录为成功 |
    | `submitted_unconfirmed` | 已点击提交,但没有观察到成功信号 | 人工复核,禁止自动重试 |
    | `failed` | 未提交或观察到失败信号 | 检查错误后再决定 |
    | `ready` | 内容已填写,尚未点击发布 | 人工检查后决定是否提交 |
    
    ### 4. 多账号
    
    ```bash
    uv run python -m scripts --profile brand-a qrcode --headless=false
    uv run python -m scripts --profile brand-a search "咖啡"
    uv run python -m scripts profiles
    ```
    
    不同 profile 使用独立的浏览器数据、Cookie 备份和会话元数据。`XHS_FP_SEED` 可临时覆盖当前进程的稳定指纹 seed。
    
    ## 安全和限制
    
    - 不要关闭内置导航间隔和互动冷却。
    - 不要运行高频批量抓取或批量互动。
    - 遇到验证码、登录页或安全验证页时停止。
    - 不要在 issue、日志或截图中提交账号信息、Cookie、完整安全参数或二维码。
    - Docker 镜像以非 root 用户运行,本地敏感状态不会进入构建上下文。
    - `XHS_ALLOW_NO_SANDBOX=true` 只适用于明确需要关闭 Chromium sandbox 的隔离环境。
    
    详见 [安全说明](docs/SECURITY.md)。
    
    ## 工程设计
    
    - [架构](docs/ARCHITECTURE.md)
    - [安装](docs/INSTALL.md)
    - [CLI API](docs/API.md)
    - [平台集成](docs/INTEGRATIONS.md)
    - [安全](docs/SECURITY.md)
    - [参考实现与来源](docs/REFERENCE.md)
    - [发布流程](docs/RELEASING.md)
    - [路线图](docs/ROADMAP.md)
    
    默认质量门:
    
    ```bash
    uv run python -m scripts.quality check
    ```
    
    CI 还会测试 Python 3.10、3.11、3.12,构建 wheel 和源码包,并验证 Docker 镜像。
    
    ## 来源与许可证
    
    仓库原创代码按 [Apache License 2.0](LICENSE) 发布。部分浏览器行为参考或改写自 Apache-2.0 项目 `xpzouying/xiaohongshu-mcp`,详情见 [第三方声明](THIRD_PARTY_NOTICES.md)。
    
    本项目与小红书官方无隶属或授权关系。使用者应自行遵守适用的平台规则、法律法规和账号安全要求。
    
  • scripts/__init__.py699 Bb655a0e00808upstream ↗
    """Python package for the Xiaohongshu Agent Skill."""
    
    from importlib.metadata import PackageNotFoundError, version
    
    from . import (
        comment,
        explore,
        feed,
        interact,
        login,
        publish,
        search,
        sop,
        strategy,
        templates,
        user,
    )
    from .client import DEFAULT_COOKIE_PATH, XiaohongshuClient, create_client
    
    try:
        __version__ = version("xiaohongshu-skill")
    except PackageNotFoundError:
        __version__ = "0+unknown"
    
    __all__ = [
        "DEFAULT_COOKIE_PATH",
        "XiaohongshuClient",
        "comment",
        "create_client",
        "explore",
        "feed",
        "interact",
        "login",
        "publish",
        "search",
        "sop",
        "strategy",
        "templates",
        "user",
    ]
    
  • scripts/__main__.py29 KB50faaf237ceeupstream ↗
    #!/usr/bin/env python
    """
    小红书 CLI 入口
    
    Reference: xiaohongshu-mcp (Apache-2.0). See THIRD_PARTY_NOTICES.md.
    """
    
    import argparse
    import json
    import logging
    import os
    import sys
    
    # Windows GBK 终端兼容性修复:强制 stdout 使用 UTF-8
    if hasattr(sys.stdout, 'reconfigure'):
        sys.stdout.reconfigure(encoding='utf-8', errors='replace')
    
    from . import (
        __version__,
        comment,
        explore,
        feed,
        interact,
        login,
        publish,
        search,
        sop,
        strategy,
        templates,
        user,
    )
    from .client import CaptchaError, XiaohongshuClient
    from .output_contracts import get_output_contracts
    from .profiles import ProfileNameError, list_profiles, profile_paths
    from .selectors import get_selector_contracts
    
    
    def format_output(data) -> str:
        """格式化输出为 JSON"""
        if data is None:
            return json.dumps({"error": "No data"}, ensure_ascii=False, indent=2)
        return json.dumps(data, ensure_ascii=False, indent=2)
    
    
    def _headless(args) -> bool:
        """从 args 解析 headless 值"""
        val = getattr(args, 'headless', 'true')
        if isinstance(val, bool):
            return val
        return val.lower() != 'false'
    
    
    def _profile(args) -> str | None:
        profile = getattr(args, "profile", None)
        return profile.strip() if isinstance(profile, str) and profile.strip() else None
    
    
    def _cookie_path(args) -> str:
        profile = _profile(args)
        paths = profile_paths(profile)
        if profile:
            os.environ["XHS_PROFILE"] = profile
        if getattr(args, "cookie", None):
            return args.cookie
        return str(paths.cookie_path)
    
    
    def _user_data_dir(args) -> str:
        profile = _profile(args)
        paths = profile_paths(profile)
        if profile:
            os.environ["XHS_PROFILE"] = profile
        return str(paths.user_data_dir)
    
    
    # ============================================================
    # 命令处理函数
    # ============================================================
    
    def cmd_login(args):
        """登录命令 — 生成二维码并等待扫码"""
        result = login.login(
            headless=_headless(args),
            cookie_path=_cookie_path(args),
            timeout=args.timeout,
        )
        print(format_output(result))
        if result.get("status") == "logged_in":
            return 0
        elif result.get("status") == "qrcode_ready":
            return 2
        return 1
    
    
    def cmd_qrcode(args):
        """
        获取二维码并等待扫码。
        如果已登录,直接返回。
        """
        cookie_path = _cookie_path(args)
        headless = _headless(args)
    
        # 1) 先快速检查是否已登录
        is_logged_in, username = login.check_login(cookie_path=cookie_path)
        if is_logged_in:
            result = {
                "status": "logged_in",
                "qrcode_path": None,
                "username": username,
                "message": "已登录",
            }
            print(format_output(result))
            return 0
    
        # 2) 未登录 → 启动可见浏览器,获取二维码并等待扫码
        client = XiaohongshuClient(headless=headless, cookie_path=cookie_path)
        try:
            client.start()
            action = login.LoginAction(client)
    
            qrcode_path, already_logged_in = action.get_wechat_qrcode()
            if already_logged_in:
                print(format_output({"status": "logged_in", "message": "已登录"}))
                return 0
    
            if qrcode_path:
                print(format_output({
                    "status": "qrcode_ready",
                    "qrcode_path": qrcode_path,
                    "message": f"请扫码登录,二维码路径: {qrcode_path}",
                }))
    
                # 等待用户扫码(最多 120 秒)
                print("等待用户扫码…(最多 120 秒)", file=sys.stderr)
                success = action.wait_for_login(timeout=120)
    
                if success:
                    print(format_output({"status": "logged_in", "message": "登录成功!"}))
                    return 0
                else:
                    print(format_output({"status": "timeout", "message": "扫码超时"}))
                    return 2
            else:
                print(format_output({"status": "error", "message": "获取二维码失败"}))
                return 1
        finally:
            client.close()
    
    
    def cmd_check_login(args):
        """检查登录状态"""
        is_logged_in, username = login.check_login(
            cookie_path=_cookie_path(args),
        )
        print(format_output({
            "is_logged_in": is_logged_in,
            "username": username,
        }))
        return 0
    
    
    def cmd_creator_login(args):
        """登录创作者中心(发布前需要)。"""
        result = login.creator_login(
            headless=_headless(args),
            cookie_path=_cookie_path(args),
            timeout=args.timeout,
        )
        print(format_output(result))
        return 0 if result.get("status") == "logged_in" else 1
    
    
    def cmd_check_creator_login(args):
        """检查创作者中心登录状态。"""
        is_logged_in = login.check_creator_login(
            cookie_path=_cookie_path(args),
            headless=_headless(args),
        )
        print(format_output({"is_logged_in": is_logged_in}))
        return 0
    
    
    def cmd_logout(args):
        """删除登录状态"""
        result = login.logout(cookie_path=_cookie_path(args), user_data_dir=_user_data_dir(args))
        print(format_output(result))
        return 0
    
    
    def cmd_profiles(args):
        """列出本地账号 profile"""
        profiles = list_profiles()
        print(format_output({
            "count": len(profiles),
            "profiles": profiles,
        }))
        return 0
    
    
    def cmd_selectors(args):
        """列出浏览器选择器契约"""
        contracts = [
            {
                "name": contract.name,
                "owner": contract.owner,
                "purpose": contract.purpose,
                "selectors": list(contract.selectors),
                "required": contract.required,
            }
            for contract in get_selector_contracts(owner=args.owner)
        ]
        print(format_output({
            "count": len(contracts),
            "contracts": contracts,
        }))
        return 0
    
    
    def cmd_contracts(args):
        """列出 CLI JSON 输出契约"""
        contracts = [
            {
                "name": contract.name,
                "command": contract.command,
                "purpose": contract.purpose,
                "required_fields": list(contract.required_fields),
                "item_fields": list(contract.item_fields),
                "notes": contract.notes,
            }
            for contract in get_output_contracts(command=args.command_name)
        ]
        print(format_output({
            "count": len(contracts),
            "contracts": contracts,
        }))
        return 0
    
    
    def cmd_search(args):
        """搜索命令"""
        results = search.search(
            keyword=args.keyword,
            sort_by=args.sort_by,
            note_type=args.note_type,
            publish_time=args.publish_time,
            search_scope=args.search_scope,
            location=args.location,
            limit=args.limit,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output({
            "count": len(results),
            "results": results,
        }))
        return 0
    
    
    def cmd_feed(args):
        """笔记详情命令"""
        detail = feed.feed_detail(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            load_comments=args.load_comments,
            max_comments=args.max_comments,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(detail))
        return 0 if detail else 1
    
    
    def cmd_user(args):
        """用户主页命令"""
        profile = user.user_profile(
            user_id=args.user_id,
            xsec_token=args.xsec_token or "",
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(profile))
        return 0 if profile else 1
    
    
    def cmd_me(args):
        """获取自己的个人主页"""
        profile = user.my_profile(
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(profile))
        return 0 if profile else 1
    
    
    def cmd_comment(args):
        """发表评论"""
        result = comment.post_comment(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            content=args.content,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_reply(args):
        """回复评论"""
        result = comment.reply_to_comment(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            comment_id=args.comment_id,
            reply_user_id=args.reply_user_id,
            content=args.content,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_like(args):
        """点赞"""
        result = interact.like(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_unlike(args):
        """取消点赞"""
        result = interact.unlike(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_collect(args):
        """收藏"""
        result = interact.collect(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_uncollect(args):
        """取消收藏"""
        result = interact.uncollect(
            feed_id=args.feed_id,
            xsec_token=args.xsec_token or "",
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_explore(args):
        """首页推荐流"""
        result = explore.explore(
            limit=args.limit,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0
    
    
    def _publish_exit_code(result):
        """Map publish confirmation states to stable CLI exit codes."""
        status = result.get("status")
        if status in {"confirmed", "ready"}:
            return 0
        if status == "submitted_unconfirmed":
            return 2
        return 1
    
    
    def cmd_publish(args):
        """发布图文笔记"""
        image_paths = [p.strip() for p in args.images.split(",") if p.strip()]
        tags = [t.strip() for t in args.tags.split(",")] if args.tags else None
        result = publish.publish_image(
            title=args.title,
            content=args.content,
            image_paths=image_paths,
            tags=tags,
            schedule_time=args.schedule_time,
            auto_publish=args.auto_publish,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return _publish_exit_code(result)
    
    
    def cmd_publish_video(args):
        """发布视频笔记"""
        tags = [t.strip() for t in args.tags.split(",")] if args.tags else None
        result = publish.publish_video(
            title=args.title,
            content=args.content,
            video_path=args.video,
            tags=tags,
            schedule_time=args.schedule_time,
            auto_publish=args.auto_publish,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return _publish_exit_code(result)
    
    
    def cmd_publish_md(args):
        """将 Markdown 渲染为图片后发布图文笔记"""
        tags = [t.strip() for t in args.tags.split(",")] if args.tags else None
    
        # 从文件或直接文本读取 Markdown
        if args.file:
            with open(args.file, "r", encoding="utf-8") as f:
                markdown_text = f.read()
        else:
            markdown_text = args.text
    
        if not markdown_text:
            print(format_output({"status": "error", "message": "需要提供 --file 或 --text"}))
            return 1
    
        result = publish.publish_markdown(
            title=args.title,
            markdown_text=markdown_text,
            extra_content=args.content or "",
            tags=tags,
            schedule_time=args.schedule_time,
            auto_publish=args.auto_publish,
            image_width=args.width,
            output_dir=args.output_dir or "",
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return _publish_exit_code(result)
    
    
    def cmd_publish_longform(args):
        """发布长文笔记"""
        result = publish.publish_longform(
            title=args.title,
            content=args.content,
            auto_publish=args.auto_publish,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return _publish_exit_code(result)
    
    
    def cmd_reply_notification(args):
        """通过通知页回复评论"""
        result = comment.reply_via_notification(
            content=args.content,
            notification_index=args.index,
            headless=_headless(args),
            cookie_path=_cookie_path(args),
        )
        print(format_output(result))
        return 0 if result.get("status") == "success" else 1
    
    
    def cmd_template(args):
        """生成写作模板"""
        result = templates.generate_template(
            topic=args.topic,
            note_type=args.type,
        )
        print(format_output(result))
        return 0
    
    
    def cmd_strategy_init(args):
        """初始化运营策略"""
        directions = [d.strip() for d in args.direction.split(",")] if args.direction else None
        result = strategy.init_strategy(
            persona=args.persona,
            target_audience=args.audience or "",
            content_direction=directions,
        )
        print(format_output(result))
        return 0
    
    
    def cmd_strategy_show(args):
        """显示运营策略"""
        result = strategy.show_strategy()
        print(format_output(result))
        return 0
    
    
    def cmd_strategy_add_post(args):
        """添加内容计划"""
        result = strategy.add_scheduled_post(
            date=args.date,
            topic=args.topic,
            note_type=args.type,
            notes=args.notes or "",
        )
        print(format_output(result))
        return 0
    
    
    def cmd_strategy_check_limit(args):
        """检查每日配额"""
        result = strategy.check_daily_limit(args.limit_type)
        print(format_output(result))
        return 0
    
    
    def cmd_sop(args):
        """执行 SOP"""
        if args.sop_type == "publish":
            result = sop.run_publish_sop(
                topic=args.topic or "未指定主题",
                note_type=args.note_type or "图文",
                auto_publish=args.auto_publish,
            )
        elif args.sop_type == "comment":
            # comment SOP 需要 JSON 格式的回复列表
            try:
                replies = json.loads(args.replies) if args.replies else []
            except json.JSONDecodeError:
                print(format_output({"status": "error", "message": "replies 参数格式错误,需要 JSON 数组"}))
                return 1
            result = sop.run_comment_sop(replies=replies)
        elif args.sop_type == "explore":
            result = sop.run_explore_sop(
                feed_count=args.feed_count,
                like_probability=args.like_prob,
                collect_probability=args.collect_prob,
                comment_probability=args.comment_prob,
            )
        else:
            print(format_output({"status": "error", "message": f"未知 SOP 类型: {args.sop_type}"}))
            return 1
    
        print(format_output(result))
        return 0 if result.get("status") in ("ready", "success") else 1
    
    
    # ============================================================
    # 入口
    # ============================================================
    
    def main():
        parser = argparse.ArgumentParser(
            description="小红书 CLI 工具",
            formatter_class=argparse.RawDescriptionHelpFormatter,
        )
    
        # 全局参数
        parser.add_argument("--version", "-V", action="version", version=f"xiaohongshu-skill {__version__}")
        parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")
        parser.add_argument("--quiet", "-q", action="store_true", help="仅输出 JSON 结果")
        parser.add_argument("--cookie", "-c", help="Cookie 文件路径", default=None)
        parser.add_argument("--profile", help="账号 profile 名称(默认沿用旧路径)", default=None)
        parser.add_argument("--headless", help="无头模式: true/false(默认 true)", default='true')
    
        subparsers = parser.add_subparsers(dest="command", help="可用命令")
    
        # login
        login_p = subparsers.add_parser("login", help="扫码登录(等待登录或超时)")
        login_p.add_argument("--timeout", "-t", type=int, default=120, help="登录超时秒数")
        login_p.add_argument("--headless", default='false', help="默认 false 以显示浏览器")
        login_p.set_defaults(func=cmd_login)
    
        # qrcode
        qr_p = subparsers.add_parser("qrcode", help="获取登录二维码并等待扫码")
        qr_p.add_argument("--headless", default='false', help="默认 false 以显示浏览器")
        qr_p.set_defaults(func=cmd_qrcode)
    
        # check-login
        chk_p = subparsers.add_parser("check-login", help="检查登录状态")
        chk_p.add_argument("--headless", default='true')
        chk_p.set_defaults(func=cmd_check_login)
    
        # creator-login
        creator_login_p = subparsers.add_parser(
            "creator-login",
            help="登录创作者中心(发布前需要)",
        )
        creator_login_p.add_argument("--timeout", "-t", type=int, default=240, help="登录超时秒数")
        creator_login_p.add_argument("--headless", default='false', help="默认 false 以显示浏览器")
        creator_login_p.set_defaults(func=cmd_creator_login)
    
        # check-creator-login
        creator_check_p = subparsers.add_parser(
            "check-creator-login",
            help="检查创作者中心登录状态",
        )
        creator_check_p.add_argument("--headless", default='true', help="无头模式: true/false(默认 true)")
        creator_check_p.set_defaults(func=cmd_check_creator_login)
    
        # logout
        logout_p = subparsers.add_parser("logout", help="删除登录状态(Cookie 和浏览器数据)")
        logout_p.set_defaults(func=cmd_logout)
    
        # profiles
        profiles_p = subparsers.add_parser("profiles", help="列出本地账号 profile")
        profiles_p.set_defaults(func=cmd_profiles)
    
        # selectors
        selectors_p = subparsers.add_parser("selectors", help="列出浏览器选择器契约")
        selectors_p.add_argument("--owner", help="按模块过滤,如 search/publish/comment")
        selectors_p.set_defaults(func=cmd_selectors)
    
        # contracts
        contracts_p = subparsers.add_parser("contracts", help="列出 CLI JSON 输出契约")
        contracts_p.add_argument("--command", dest="command_name", help="按命令过滤,如 search/publish")
        contracts_p.set_defaults(func=cmd_contracts)
    
        # search
        s_p = subparsers.add_parser("search", help="搜索内容")
        s_p.add_argument("keyword", help="搜索关键词")
        s_p.add_argument("--sort-by", help="排序方式")
        s_p.add_argument("--note-type", help="笔记类型")
        s_p.add_argument("--publish-time", help="发布时间")
        s_p.add_argument("--search-scope", help="搜索范围")
        s_p.add_argument("--location", help="位置距离")
        s_p.add_argument("--limit", "-n", type=int, default=10, help="返回数量")
        s_p.add_argument("--headless", default='true')
        s_p.set_defaults(func=cmd_search)
    
        # feed
        f_p = subparsers.add_parser("feed", help="获取笔记详情")
        f_p.add_argument("feed_id", help="笔记 ID")
        f_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        f_p.add_argument("--load-comments", "-l", action="store_true", help="加载评论")
        f_p.add_argument("--max-comments", "-m", type=int, default=0, help="最大评论数")
        f_p.add_argument("--headless", default='true')
        f_p.set_defaults(func=cmd_feed)
    
        # user
        u_p = subparsers.add_parser("user", help="获取用户主页")
        u_p.add_argument("user_id", help="用户 ID")
        u_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        u_p.add_argument("--headless", default='true')
        u_p.set_defaults(func=cmd_user)
    
        # me (获取自己的主页)
        me_p = subparsers.add_parser("me", help="获取自己的个人主页")
        me_p.add_argument("--headless", default='true')
        me_p.set_defaults(func=cmd_me)
    
        # comment (发表评论)
        cmt_p = subparsers.add_parser("comment", help="发表评论")
        cmt_p.add_argument("feed_id", help="笔记 ID")
        cmt_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        cmt_p.add_argument("--content", required=True, help="评论内容")
        cmt_p.add_argument("--headless", default='true')
        cmt_p.set_defaults(func=cmd_comment)
    
        # reply (回复评论)
        rpl_p = subparsers.add_parser("reply", help="回复评论")
        rpl_p.add_argument("feed_id", help="笔记 ID")
        rpl_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        rpl_p.add_argument("--comment-id", required=True, help="目标评论 ID")
        rpl_p.add_argument("--reply-user-id", required=True, help="被回复用户 ID")
        rpl_p.add_argument("--content", required=True, help="回复内容")
        rpl_p.add_argument("--headless", default='true')
        rpl_p.set_defaults(func=cmd_reply)
    
        # like (点赞)
        like_p = subparsers.add_parser("like", help="点赞笔记")
        like_p.add_argument("feed_id", help="笔记 ID")
        like_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        like_p.add_argument("--headless", default='true')
        like_p.set_defaults(func=cmd_like)
    
        # unlike (取消点赞)
        unlike_p = subparsers.add_parser("unlike", help="取消点赞")
        unlike_p.add_argument("feed_id", help="笔记 ID")
        unlike_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        unlike_p.add_argument("--headless", default='true')
        unlike_p.set_defaults(func=cmd_unlike)
    
        # collect (收藏)
        col_p = subparsers.add_parser("collect", help="收藏笔记")
        col_p.add_argument("feed_id", help="笔记 ID")
        col_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        col_p.add_argument("--headless", default='true')
        col_p.set_defaults(func=cmd_collect)
    
        # uncollect (取消收藏)
        ucol_p = subparsers.add_parser("uncollect", help="取消收藏")
        ucol_p.add_argument("feed_id", help="笔记 ID")
        ucol_p.add_argument("xsec_token", nargs="?", help="xsec_token")
        ucol_p.add_argument("--headless", default='true')
        ucol_p.set_defaults(func=cmd_uncollect)
    
        # explore (首页推荐流)
        exp_p = subparsers.add_parser("explore", help="获取首页推荐流")
        exp_p.add_argument("--limit", "-n", type=int, default=20, help="返回数量")
        exp_p.add_argument("--headless", default='true')
        exp_p.set_defaults(func=cmd_explore)
    
        # publish (发布图文笔记)
        pub_p = subparsers.add_parser("publish", help="发布图文笔记")
        pub_p.add_argument("--title", required=True, help="标题(建议 <=20 字)")
        pub_p.add_argument("--content", required=True, help="正文内容")
        pub_p.add_argument("--images", required=True, help="图片路径,逗号分隔")
        pub_p.add_argument("--tags", help="话题标签,逗号分隔")
        pub_p.add_argument("--schedule-time", help="定时发布(格式: 2025-01-01 12:00)")
        pub_p.add_argument("--auto-publish", action="store_true", help="自动点击发布(默认停在发布按钮处)")
        pub_p.add_argument("--headless", default='true')
        pub_p.set_defaults(func=cmd_publish)
    
        # publish-video (发布视频笔记)
        pubv_p = subparsers.add_parser("publish-video", help="发布视频笔记")
        pubv_p.add_argument("--title", required=True, help="标题")
        pubv_p.add_argument("--content", required=True, help="正文内容")
        pubv_p.add_argument("--video", required=True, help="视频文件路径")
        pubv_p.add_argument("--tags", help="话题标签,逗号分隔")
        pubv_p.add_argument("--schedule-time", help="定时发布(格式: 2025-01-01 12:00)")
        pubv_p.add_argument("--auto-publish", action="store_true", help="自动点击发布")
        pubv_p.add_argument("--headless", default='true')
        pubv_p.set_defaults(func=cmd_publish_video)
    
        # publish-md (Markdown 转图片后发布)
        pubmd_p = subparsers.add_parser("publish-md", help="Markdown 渲染为图片后发布")
        pubmd_p.add_argument("--title", required=True, help="标题")
        pubmd_p.add_argument("--file", help="Markdown 文件路径")
        pubmd_p.add_argument("--text", help="Markdown 文本(与 --file 二选一)")
        pubmd_p.add_argument("--content", help="正文区额外文字说明")
        pubmd_p.add_argument("--tags", help="话题标签,逗号分隔")
        pubmd_p.add_argument("--schedule-time", help="定时发布")
        pubmd_p.add_argument("--auto-publish", action="store_true", help="自动点击发布")
        pubmd_p.add_argument("--width", type=int, default=1080, help="图片宽度(默认 1080)")
        pubmd_p.add_argument("--output-dir", help="图片输出目录(默认临时目录)")
        pubmd_p.add_argument("--headless", default='true')
        pubmd_p.set_defaults(func=cmd_publish_md)
    
        # publish-longform (发布长文笔记)
        publf_p = subparsers.add_parser("publish-longform", help="发布长文笔记(创作者中心写长文)")
        publf_p.add_argument("--title", required=True, help="标题")
        publf_p.add_argument("--content", required=True, help="正文内容")
        publf_p.add_argument("--auto-publish", action="store_true", help="自动点击发布")
        publf_p.add_argument("--headless", default='true')
        publf_p.set_defaults(func=cmd_publish_longform)
    
        # reply-notification (通过通知页回复)
        rpln_p = subparsers.add_parser("reply-notification", help="通过通知页回复评论")
        rpln_p.add_argument("--content", required=True, help="回复内容")
        rpln_p.add_argument("--index", type=int, default=0, help="通知索引(默认第一条)")
        rpln_p.add_argument("--headless", default='true')
        rpln_p.set_defaults(func=cmd_reply_notification)
    
        # template (写作模板)
        tmpl_p = subparsers.add_parser("template", help="生成写作模板")
        tmpl_p.add_argument("--topic", required=True, help="主题关键词")
        tmpl_p.add_argument("--type", default="图文", help="笔记类型(图文/视频/长文)")
        tmpl_p.set_defaults(func=cmd_template)
    
        # strategy init (初始化运营策略)
        stri_p = subparsers.add_parser("strategy-init", help="初始化运营策略")
        stri_p.add_argument("--persona", required=True, help="账号人设(如\"旅行博主\")")
        stri_p.add_argument("--audience", help="目标受众")
        stri_p.add_argument("--direction", help="内容方向,逗号分隔")
        stri_p.set_defaults(func=cmd_strategy_init)
    
        # strategy show (显示运营策略)
        strs_p = subparsers.add_parser("strategy-show", help="显示当前运营策略")
        strs_p.set_defaults(func=cmd_strategy_show)
    
        # strategy add-post (添加内容计划)
        strap_p = subparsers.add_parser("strategy-add-post", help="添加内容日历条目")
        strap_p.add_argument("--date", required=True, help="日期(YYYY-MM-DD)")
        strap_p.add_argument("--topic", required=True, help="选题")
        strap_p.add_argument("--type", default="图文", help="笔记类型")
        strap_p.add_argument("--notes", help="备注")
        strap_p.set_defaults(func=cmd_strategy_add_post)
    
        # strategy check-limit (检查配额)
        strcl_p = subparsers.add_parser("strategy-check-limit", help="检查每日互动配额")
        strcl_p.add_argument("--limit-type", required=True, help="操作类型(likes/comments/replies/collects/publishes)")
        strcl_p.set_defaults(func=cmd_strategy_check_limit)
    
        # sop (SOP 编排)
        sop_p = subparsers.add_parser("sop", help="执行 SOP 编排")
        sop_p.add_argument("--type", dest="sop_type", required=True, help="SOP 类型(publish/comment/explore)")
        sop_p.add_argument("--topic", help="选题(publish SOP 用)")
        sop_p.add_argument("--note-type", help="笔记类型(publish SOP 用)")
        sop_p.add_argument("--auto-publish", action="store_true", help="自动发布(publish SOP 用)")
        sop_p.add_argument("--replies", help="回复列表 JSON(comment SOP 用)")
        sop_p.add_argument("--feed-count", type=int, default=10, help="浏览笔记数(explore SOP 用)")
        sop_p.add_argument("--like-prob", type=float, default=0.3, help="点赞概率(explore SOP 用)")
        sop_p.add_argument("--collect-prob", type=float, default=0.1, help="收藏概率(explore SOP 用)")
        sop_p.add_argument("--comment-prob", type=float, default=0.05, help="评论概率(explore SOP 用)")
        sop_p.set_defaults(func=cmd_sop)
    
        args = parser.parse_args()
    
        # 根据 --verbose / --quiet 设置日志级别
        if args.verbose:
            logging.getLogger().setLevel(logging.DEBUG)
        elif args.quiet:
            logging.getLogger().setLevel(logging.ERROR)
    
        if not args.command:
            parser.print_help()
            return 0
    
        try:
            return args.func(args)
        except CaptchaError as e:
            print(format_output({
                "status": "error",
                "error_type": "CaptchaError",
                "message": str(e),
                "captcha_url": e.captcha_url,
            }))
            return 1
        except ProfileNameError as e:
            print(format_output({
                "status": "error",
                "error_type": "ProfileNameError",
                "message": str(e),
            }))
            return 1
        except Exception as e:
            print(format_output({
                "status": "error",
                "error_type": type(e).__name__,
                "message": str(e),
            }))
            return 1
    
    
    if __name__ == "__main__":
        sys.exit(main())
    
  • scripts/_logging.py775 B63e9b420f015upstream ↗
    """
    日志工具模块
    
    为 CLI 工具提供统一的日志接口。默认 WARNING 级别,
    通过 --verbose 提升到 DEBUG,--quiet 降低到 ERROR。
    """
    
    import logging
    import sys
    
    
    def get_logger(name: str) -> logging.Logger:
        """
        获取命名的 logger 实例。
    
        首次调用时自动配置 handler:输出到 stderr,
        格式为 "[LEVEL] name: message",默认级别 WARNING。
        """
        logger = logging.getLogger(name)
        if not logger.handlers:
            handler = logging.StreamHandler(sys.stderr)
            handler.setFormatter(logging.Formatter(
                '[%(levelname)s] %(name)s: %(message)s'
            ))
            logger.addHandler(handler)
            logger.setLevel(logging.WARNING)  # 默认 WARNING,--verbose 改 DEBUG
        return logger
    
  • scripts/_utils.py1.9 KB819ff6c951c2upstream ↗
    """
    小红书公共工具函数
    
    提取各模块中重复使用的辅助逻辑。
    """
    
    from typing import Any
    
    
    def is_element_blocked(page, elem):
        """检测元素是否被其他元素遮挡
    
        Go 参考: publish.go:187-203 isElementBlocked
        通过 JS getBoundingClientRect + elementFromPoint 判断元素中心点
        是否被其他 DOM 节点遮挡。
        """
        result = elem.evaluate("""(el) => {
            const rect = el.getBoundingClientRect();
            if (rect.width === 0 || rect.height === 0) return true;
            const x = rect.left + rect.width / 2;
            const y = rect.top + rect.height / 2;
            const target = document.elementFromPoint(x, y);
            return !(target === el || el.contains(target));
        }""")
        return result
    
    
    def make_feed_url(feed_id: str, xsec_token: str, xsec_source: str = "pc_feed") -> str:
        """构建笔记详情 URL
    
        在 comment.py, feed.py, interact.py 中原本各自定义,现统一到此。
        """
        return f"https://www.xiaohongshu.com/explore/{feed_id}?xsec_token={xsec_token}&xsec_source={xsec_source}"
    
    
    def unwrap_value(obj: Any) -> Any:
        """解包 Vue ref 代理对象
    
        处理 Playwright 返回的 JavaScript 对象被包装成 {value: ...} 或 {_value: ...} 的情况。
        同时兼容 json.loads 产生的 dict 和 Playwright 返回的属性访问对象。
    
        原逻辑在 search.py, feed.py, explore.py, interact.py, user.py 的 JS 代码中重复出现,
        现提供 Python 侧统一解包函数供相关模块使用。
        """
        if isinstance(obj, dict):
            if obj.get('value') is not None:
                return obj['value']
            if obj.get('_value') is not None:
                return obj['_value']
        else:
            if hasattr(obj, 'value') and obj.value is not None:
                return obj.value
            if hasattr(obj, '_value') and obj._value is not None:
                return obj._value
        return obj
    
  • scripts/client.py21 KB1a0e70a68d84upstream ↗
    """
    小红书浏览器客户端封装
    
    Reference: xiaohongshu-mcp (Apache-2.0), reimplemented with Python Playwright. See THIRD_PARTY_NOTICES.md.
    """
    
    import hashlib
    import json
    import os
    import random
    import time
    from typing import Any, Dict, Optional
    
    from ._logging import get_logger
    from ._utils import unwrap_value
    from .profiles import env_profile, profile_paths
    from .session_store import atomic_write_json, resolve_fingerprint_seed
    
    log = get_logger(__name__)
    
    try:
        from playwright.sync_api import (
            Browser,
            BrowserContext,
            Page,
            Playwright,
            sync_playwright,
        )
    except ImportError:
        print("请先安装 playwright: pip install playwright && playwright install chromium")
        raise
    
    
    # Cookie 文件路径(备份用)
    DEFAULT_COOKIE_PATH = str(profile_paths().cookie_path)
    
    # 持久化浏览器数据目录(保存 cookies + localStorage + sessionStorage 等全部会话状态)
    DEFAULT_USER_DATA_DIR = str(profile_paths().user_data_dir)
    
    # 验证码/安全拦截页面的 URL 特征
    CAPTCHA_URL_PATTERNS = [
        'captcha',
        'security-verification',
        'website-login/captcha',
        'verifyType',
        'verifyBiz',
    ]
    
    # 验证码页面的标题特征
    CAPTCHA_TITLE_PATTERNS = [
        '安全验证',
        '验证码',
        'captcha',
        'Security Verification',
    ]
    
    
    class CaptchaError(Exception):
        """触发验证码异常"""
        def __init__(self, url: str, message: str = ""):
            self.captcha_url = url
            super().__init__(message or f"触发安全验证: {url}")
    
    
    class XiaohongshuClient:
        """小红书浏览器客户端"""
    
        # 频率控制参数
        MIN_INTERVAL = 3.0       # 两次导航最小间隔(秒)
        MAX_INTERVAL = 6.0       # 两次导航最大间隔(秒)
        BURST_THRESHOLD = 5      # 连续请求阈值,超过后增加额外冷却
        BURST_COOLDOWN = 10.0    # 连续请求冷却时间(秒)
    
        # 外部 stealth.js 覆盖路径(用户可选)
        STEALTH_JS_PATH = os.path.join(os.path.expanduser("~"), ".xiaohongshu", "stealth.js")
    
        def __init__(
            self,
            headless: bool = True,
            cookie_path: Optional[str] = None,
            user_data_dir: Optional[str] = None,
            timeout: int = 60,
        ):
            self.headless = headless
            paths = profile_paths(env_profile())
            self.cookie_path = cookie_path or str(paths.cookie_path)
            self.user_data_dir = user_data_dir or str(paths.user_data_dir)
            self.session_path = str(
                paths.session_path
                if cookie_path is None
                else os.path.join(os.path.dirname(self.cookie_path), "session.json")
            )
            self.timeout = timeout * 1000  # 转换为毫秒
    
            self.playwright: Optional[Playwright] = None
            self.browser: Optional[Browser] = None
            self.context: Optional[BrowserContext] = None
            self.page: Optional[Page] = None
    
            # 请求计时器(实例变量,避免跨实例干扰)
            self._last_navigate_time: float = 0.0
            self._navigate_count: int = 0
            self._session_start: float = 0.0
    
            # start() 时解析 profile seed,避免构造客户端就读取会话文件。
            self._stealth_js = ""
    
        def __enter__(self):
            self.start()
            return self
    
        def __exit__(self, exc_type, exc_val, exc_tb):
            self.close()
    
        def _load_stealth_js(self, seed: str) -> str:
            """Build stealth JS from a stable profile seed and optional local overrides."""
            seed_number = int.from_bytes(
                hashlib.sha256(seed.encode("utf-8")).digest()[:4],
                "big",
            )
            js = self.STEALTH_JS.replace("__XHS_FINGERPRINT_SEED__", str(seed_number))
            if os.path.exists(self.STEALTH_JS_PATH):
                try:
                    with open(self.STEALTH_JS_PATH, "r", encoding="utf-8") as handle:
                        external = handle.read()
                    if external.strip():
                        js += "\n// === External stealth.js overrides ===\n" + external
                        log.info("Loaded external stealth.js overrides")
                except Exception:
                    log.warning("Unable to load external stealth.js overrides")
            return js
    
        # 反检测隐身脚本:覆盖 headless Chromium 的自动化特征
        STEALTH_JS = """
        // 1. 移除 navigator.webdriver 标记
        Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
    
        // 2. 伪造 chrome 运行时对象
        if (!window.chrome) { window.chrome = {}; }
        if (!window.chrome.runtime) {
            window.chrome.runtime = {
                onMessage: { addListener: function(){}, removeListener: function(){} },
                sendMessage: function(){},
                connect: function(){ return { onMessage: { addListener: function(){} }, postMessage: function(){} }; }
            };
        }
    
        // 3. 伪造插件列表(headless 默认为空)
        Object.defineProperty(navigator, 'plugins', {
            get: () => {
                const arr = [
                    { name: 'Chrome PDF Plugin', filename: 'internal-pdf-viewer', description: 'Portable Document Format' },
                    { name: 'Chrome PDF Viewer', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai', description: '' },
                    { name: 'Native Client', filename: 'internal-nacl-plugin', description: '' },
                ];
                arr.item = (i) => arr[i] || null;
                arr.namedItem = (n) => arr.find(p => p.name === n) || null;
                arr.refresh = () => {};
                return arr;
            }
        });
    
        // 4. 伪造语言列表
        Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en-US', 'en'] });
    
        // 5. 修复 Permissions API(headless 返回异常状态)
        if (navigator.permissions) {
            const origQuery = navigator.permissions.query.bind(navigator.permissions);
            navigator.permissions.query = (params) => {
                if (params.name === 'notifications') {
                    return Promise.resolve({ state: Notification.permission });
                }
                return origQuery(params);
            };
        }
    
        // 6. 伪造 WebGL 渲染器信息
        const getParameter = WebGLRenderingContext.prototype.getParameter;
        WebGLRenderingContext.prototype.getParameter = function(param) {
            if (param === 37445) return 'Intel Inc.';
            if (param === 37446) return 'Intel Iris OpenGL Engine';
            return getParameter.call(this, param);
        };
    
        // 7. 隐藏自动化相关的 CDP 痕迹
        // 移除 Error.stack 中的 CDP Runtime.enable 调用痕迹
        const origStackGetter = Object.getOwnPropertyDescriptor(Error.prototype, 'stack').get;
        Object.defineProperty(Error.prototype, 'stack', {
            get: function() {
                const stack = origStackGetter.call(this);
                if (stack && typeof stack === 'string') {
                    return stack.split('\\n').filter(line =>
                        !line.includes('__puppeteer_') &&
                        !line.includes('__playwright_') &&
                        !line.includes('callFunctionOn') &&
                        !line.includes('evaluateOnCallFrame')
                    ).join('\\n');
                }
                return stack;
            }
        });
    
        // 8. Stable per-profile Canvas fingerprint
        const __xhsFingerprintSeed = __XHS_FINGERPRINT_SEED__;
        const __xhsCanvasNoise = (width, height) => {
            let state = (__xhsFingerprintSeed
                ^ Math.imul(width + 1, 0x9e3779b1)
                ^ Math.imul(height + 1, 0x85ebca6b)) >>> 0;
            state = (state + 0x6d2b79f5) >>> 0;
            let mixed = Math.imul(state ^ (state >>> 15), state | 1);
            mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61);
            return ((mixed ^ (mixed >>> 14)) >>> 0);
        };
        const __xhsNoisyCanvas = (canvas) => {
            if (!canvas.width || !canvas.height) return canvas;
            const clone = document.createElement('canvas');
            clone.width = canvas.width;
            clone.height = canvas.height;
            const ctx = clone.getContext('2d');
            if (!ctx) return canvas;
            ctx.drawImage(canvas, 0, 0);
            try {
                const imageData = ctx.getImageData(0, 0, 1, 1);
                const noise = __xhsCanvasNoise(canvas.width, canvas.height);
                imageData.data[0] ^= noise & 0xff;
                imageData.data[1] ^= (noise >>> 8) & 0xff;
                imageData.data[2] ^= (noise >>> 16) & 0xff;
                ctx.putImageData(imageData, 0, 0);
            } catch (_) {
                return canvas;
            }
            return clone;
        };
        const origToDataURL = HTMLCanvasElement.prototype.toDataURL;
        HTMLCanvasElement.prototype.toDataURL = function() {
            return origToDataURL.apply(__xhsNoisyCanvas(this), arguments);
        };
        const origToBlob = HTMLCanvasElement.prototype.toBlob;
        HTMLCanvasElement.prototype.toBlob = function() {
            return origToBlob.apply(__xhsNoisyCanvas(this), arguments);
        };
    
        // 9. 修复 headless 模式下的 outerWidth/outerHeight
        Object.defineProperty(window, 'outerWidth', { get: () => window.innerWidth });
        Object.defineProperty(window, 'outerHeight', { get: () => window.innerHeight + 100 });
        """
    
        def start(self):
            """启动浏览器(持久化上下文,自动保存全部会话状态)"""
            self.playwright = sync_playwright().start()
            os.makedirs(self.user_data_dir, exist_ok=True)
            seed = resolve_fingerprint_seed(self.session_path)
            self._stealth_js = self._load_stealth_js(seed)
            browser_args = [
                "--disable-blink-features=AutomationControlled",
                "--disable-features=AutomationControlled",
                "--disable-infobars",
                "--disable-dev-shm-usage",
                "--disable-gpu",
            ]
            if os.environ.get("XHS_ALLOW_NO_SANDBOX", "").strip().lower() in {
                "1",
                "true",
                "yes",
                "on",
            }:
                browser_args.append("--no-sandbox")
    
            # 使用持久化上下文:自动保存 cookies + localStorage + sessionStorage + indexedDB
            self.context = self.playwright.chromium.launch_persistent_context(
                user_data_dir=self.user_data_dir,
                headless=self.headless,
                viewport={'width': 1920, 'height': 1080},
                user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
                locale='zh-CN',
                timezone_id='Asia/Shanghai',
                args=browser_args,
                ignore_default_args=['--enable-automation'],
            )
            self.browser = None  # persistent context 无需单独的 browser 对象
    
            # 注入反检测隐身脚本(在每个新页面加载前执行)
            self.context.add_init_script(self._stealth_js)
    
            # 如果持久化目录是新的但有旧 cookie 备份文件,迁移恢复
            if not self.context.cookies() and os.path.exists(self.cookie_path):
                self._load_cookies()
                log.info("已从备份文件迁移 Cookie 到持久化上下文")
    
            # 复用持久化上下文的已有页面,或创建新页面
            if self.context.pages:
                self.page = self.context.pages[0]
            else:
                self.page = self.context.new_page()
            self.page.set_default_timeout(self.timeout)
    
        def close(self):
            """关闭浏览器"""
            # 备份 Cookie 到文件(持久化上下文已自动保存到磁盘)
            self._save_cookies()
    
            if self.page:
                self.page.close()
            if self.context:
                self.context.close()
            # persistent context 无需单独关闭 browser
            if self.playwright:
                self.playwright.stop()
    
        def _load_cookies(self):
            """Load the legacy cookie-list backup without changing its format."""
            if not os.path.exists(self.cookie_path) or not self.context:
                return
    
            try:
                with open(self.cookie_path, "r", encoding="utf-8") as handle:
                    cookies = json.load(handle)
                if not isinstance(cookies, list) or not all(
                    isinstance(cookie, dict) for cookie in cookies
                ):
                    raise ValueError("cookie backup must be a JSON array")
                if cookies:
                    self.context.add_cookies(cookies)
                    log.info("Loaded %d cookies from backup", len(cookies))
            except Exception:
                log.warning("Unable to load cookie backup; continuing with browser profile")
    
        def _save_cookies(self):
            """Atomically save cookies in the legacy JSON-array format."""
            if not self.context:
                return
    
            try:
                cookies = self.context.cookies()
                atomic_write_json(self.cookie_path, cookies)
                log.info("Saved %d cookies to backup", len(cookies))
            except Exception:
                log.warning("Unable to save cookie backup")
    
        def _throttle(self):
            """请求频率控制:模拟人类浏览节奏"""
            now = time.time()
    
            # 初始化会话起点
            if self._session_start == 0:
                self._session_start = now
    
            # 计算距上次导航的间隔
            elapsed = now - self._last_navigate_time if self._last_navigate_time > 0 else 999
    
            # 连续请求达到阈值 → 额外冷却
            if self._navigate_count > 0 and self._navigate_count % self.BURST_THRESHOLD == 0:
                cooldown = self.BURST_COOLDOWN + random.uniform(0, 3)
                if elapsed < cooldown:
                    wait = cooldown - elapsed
                    log.debug("反爬保护: 连续请求 %d 次,冷却 %.1fs...", self._navigate_count, wait)
                    time.sleep(wait)
            elif elapsed < self.MIN_INTERVAL:
                # 普通间隔控制
                wait = random.uniform(self.MIN_INTERVAL, self.MAX_INTERVAL) - elapsed
                if wait > 0:
                    time.sleep(wait)
    
            self._last_navigate_time = time.time()
            self._navigate_count += 1
    
        def _check_captcha(self) -> bool:
            """
            检测当前页面是否被重定向到验证码页面
    
            Returns:
                True 表示触发了验证码
            """
            if not self.page:
                return False
    
            try:
                current_url = self.page.url.lower()
                for pattern in CAPTCHA_URL_PATTERNS:
                    if pattern in current_url:
                        return True
    
                page_title = self.page.title().lower()
                for pattern in CAPTCHA_TITLE_PATTERNS:
                    if pattern.lower() in page_title:
                        return True
            except Exception:
                pass
    
            return False
    
        def _handle_captcha(self):
            """
            处理验证码拦截:抛出异常通知调用方
    
            Raises:
                CaptchaError
            """
            url = self.page.url if self.page else "unknown"
            raise CaptchaError(
                url=url,
                message=(
                    f"触发小红书安全验证!\n"
                    f"  验证页面: {url}\n"
                    f"  本次会话已请求 {self._navigate_count} 次\n"
                    f"  建议: 1) 等待几分钟后重试  2) 用 --headless=false 手动过验证码  "
                    f"3) 重新扫码登录"
                ),
            )
    
        def navigate(self, url: str, wait_until: str = "domcontentloaded"):
            """导航到指定 URL(含频率控制和验证码检测)"""
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            # 频率控制
            self._throttle()
    
            self.page.goto(url, wait_until=wait_until)
            # 等待页面稳定
            time.sleep(random.uniform(1.5, 3.0))
            # 尝试等待 networkidle,但不强制
            try:
                self.page.wait_for_load_state("networkidle", timeout=8000)
            except Exception:
                pass
    
            # 验证码检测
            if self._check_captcha():
                self._handle_captcha()
    
        def wait_for_initial_state(self, timeout: int = 30000, retries: int = 2):
            """等待 __INITIAL_STATE__ 加载完成,带重试和回退"""
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            for attempt in range(retries + 1):
                # 先检测验证码
                if self._check_captcha():
                    self._handle_captcha()
    
                try:
                    self.page.wait_for_function(
                        "() => window.__INITIAL_STATE__ !== undefined",
                        timeout=timeout,
                    )
                    return
                except Exception:
                    if attempt < retries:
                        log.warning("__INITIAL_STATE__ 等待超时,刷新重试 (%d/%d)...", attempt + 1, retries)
                        self.page.reload(wait_until="domcontentloaded")
                        time.sleep(random.uniform(2, 4))
                        # 刷新后再检测验证码
                        if self._check_captcha():
                            self._handle_captcha()
                    else:
                        log.warning("__INITIAL_STATE__ 加载超时,尝试继续执行")
    
        def get_initial_state(self) -> Dict[str, Any]:
            """获取 __INITIAL_STATE__ 数据"""
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            # 使用 structuredClone 或手动提取需要的部分,避免循环引用
            result = self.page.evaluate("""() => {
                if (!window.__INITIAL_STATE__) {
                    return '';
                }
                // 只提取需要的顶层结构
                const state = window.__INITIAL_STATE__;
                const result = {};
                if (state.search) result.search = state.search;
                if (state.feed) result.feed = state.feed;
                if (state.note) result.note = state.note;
                if (state.user) result.user = state.user;
                return JSON.stringify(result);
            }""")
    
            if not result:
                return {}
    
            return json.loads(result)
    
        def get_data_by_path(self, path: str) -> Any:
            """
            根据路径获取 __INITIAL_STATE__ 中的数据
    
            例如: "search.feeds", "note.noteDetailMap", "user.userPageData"
            """
            state = self.get_initial_state()
    
            keys = path.split('.')
            current = state
    
            for key in keys:
                if current is None:
                    return None
                if isinstance(current, dict):
                    current = current.get(key)
                else:
                    return None
                current = unwrap_value(current)
    
            return current
    
        # DEPRECATED: use login.LoginAction.check_login_status() instead
        def check_login_status(self) -> bool:
            """检查登录状态(已废弃,请使用 login.LoginAction)"""
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            # 访问首页
            self.navigate("https://www.xiaohongshu.com/explore")
            time.sleep(1)
    
            # 检查是否存在登录后的元素
            try:
                element = self.page.locator('.main-container .user .link-wrapper .channel')
                count = element.count()
                return count > 0
            except Exception:
                return False
    
        # DEPRECATED: use login.LoginAction.get_wechat_qrcode() instead
        def get_qrcode(self) -> Optional[str]:
            """获取登录二维码(已废弃,请使用 login.LoginAction)"""
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            # 访问首页触发二维码弹窗
            self.navigate("https://www.xiaohongshu.com/explore")
            time.sleep(2)
    
            # 检查是否已登录
            if self.check_login_status():
                return None
    
            # 获取二维码图片
            try:
                qrcode = self.page.locator('.login-container .qrcode-img')
                src = qrcode.get_attribute('src')
                return src
            except Exception:
                return None
    
        # DEPRECATED: use login.LoginAction.wait_for_login() instead
        def wait_for_login(self, timeout: int = 120) -> bool:
            """
            等待用户扫码登录
    
            Args:
                timeout: 超时时间(秒)
    
            Returns:
                是否登录成功
            """
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            start_time = time.time()
            while time.time() - start_time < timeout:
                if self.check_login_status():
                    # 保存登录后的 Cookie
                    self._save_cookies()
                    return True
                time.sleep(1)
    
            return False
    
        def scroll_to_bottom(self, distance: int = 500):
            """滚动页面"""
            if not self.page:
                raise RuntimeError("浏览器未启动")
    
            self.page.evaluate(f"window.scrollBy(0, {distance})")
            time.sleep(0.5)
    
    
    def create_client(
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
        user_data_dir: str = DEFAULT_USER_DATA_DIR,
        timeout: int = 60,
    ) -> XiaohongshuClient:
        """创建小红书客户端的便捷函数"""
        return XiaohongshuClient(
            headless=headless,
            cookie_path=cookie_path,
            user_data_dir=user_data_dir,
            timeout=timeout,
        )
    
  • scripts/comment.py19 KB79b8818596fdupstream ↗
    """
    小红书评论模块
    
    Reference: xiaohongshu-mcp/comment_feed.go (Apache-2.0). See THIRD_PARTY_NOTICES.md.
    评论安全校验:长度校验、人性化延迟、频率检测
    """
    
    import random
    import sys
    import time
    from typing import Any, Dict, Optional
    
    from ._utils import make_feed_url
    from .client import DEFAULT_COOKIE_PATH, XiaohongshuClient
    
    # 评论安全常量
    MAX_COMMENT_LENGTH = 280
    TYPING_DELAY_MIN = 30   # 每字符输入延迟下限(ms)
    TYPING_DELAY_MAX = 80   # 每字符输入延迟上限(ms)
    PRE_SUBMIT_DELAY_MIN = 1.5  # 提交前等待下限(秒)
    PRE_SUBMIT_DELAY_MAX = 3.0  # 提交前等待上限(秒)
    POST_SUBMIT_COOLDOWN_MIN = 8   # 提交后冷却下限(秒)
    POST_SUBMIT_COOLDOWN_MAX = 15  # 提交后冷却上限(秒)
    
    
    class CommentAction:
        """评论动作"""
    
        def __init__(self, client: XiaohongshuClient):
            self.client = client
    
        def _make_feed_url(self, feed_id: str, xsec_token: str, xsec_source: str = "pc_feed") -> str:
            """构建笔记详情 URL(委托给 _utils.make_feed_url)"""
            return make_feed_url(feed_id, xsec_token, xsec_source)
    
        def _navigate_to_feed(self, feed_id: str, xsec_token: str):
            """导航到笔记详情页并等待加载"""
            url = self._make_feed_url(feed_id, xsec_token)
            print(f"打开笔记详情页: {url}", file=sys.stderr)
            self.client.navigate(url)
            self.client.wait_for_initial_state()
            time.sleep(2)
    
        @staticmethod
        def validate_comment(content: str) -> Optional[str]:
            """
            评论内容校验
    
            Returns:
                None 表示校验通过,否则返回错误原因
            """
            if not content or not content.strip():
                return "评论内容不能为空"
            if len(content) > MAX_COMMENT_LENGTH:
                return f"评论内容超长({len(content)}/{MAX_COMMENT_LENGTH})"
            return None
    
        def _check_rate_limit(self) -> bool:
            """
            检测是否触发了评论频率限制
    
            Returns:
                True 表示被限流
            """
            page = self.client.page
            try:
                # 检查常见的频率限制提示
                rate_limit_selectors = [
                    'div.d-toast:has-text("频繁")',
                    'div.d-toast:has-text("操作太快")',
                    'div.d-toast:has-text("稍后再试")',
                    'div.d-toast:has-text("限制")',
                ]
                for sel in rate_limit_selectors:
                    toast = page.locator(sel)
                    if toast.count() > 0 and toast.first.is_visible():
                        toast_text = toast.first.text_content()
                        print(f"检测到频率限制: {toast_text}", file=sys.stderr)
                        return True
            except Exception:
                pass
            return False
    
        def _verify_input_placeholder(self, expected_hint: Optional[str] = None) -> bool:
            """
            验证输入框 placeholder 是否正确
            确保输入框已正确激活,防止误输入
    
            Args:
                expected_hint: 期望的 placeholder 文本片段(如 "回复 用户名")
    
            Returns:
                True 表示输入框状态正确
            """
            if not expected_hint:
                return True
    
            page = self.client.page
            try:
                placeholder = page.locator('div.input-box div.content-edit p.content-input')
                if placeholder.count() > 0:
                    attr = placeholder.first.get_attribute('data-placeholder') or ''
                    text = placeholder.first.text_content() or ''
                    if expected_hint in attr or expected_hint in text:
                        print(f"输入框验证通过: {attr or text}", file=sys.stderr)
                        return True
                    else:
                        print(f"输入框 placeholder 不匹配: 期望含「{expected_hint}」, 实际「{attr or text}」", file=sys.stderr)
            except Exception:
                pass
            return True  # 获取失败时不阻断流程
    
        def _find_comment_with_scroll(self, comment_id: str, reply_user_id: str, max_attempts: int = 100):
            """滚动查找目标评论元素(支持懒加载,从 Go comment_feed.go:157-273 移植)
    
            优先匹配 #comment-{comment_id},然后扫描 [data-user-id="{user_id}"]。
            最多 100 次滚动尝试,10 次未增长则检测 end-container 终止。
            """
            page = self.client.page
            stagnant = 0
            last_comment_count = 0
    
            for attempt in range(max_attempts):
                # Priority 1: check for #comment-{comment_id}
                try:
                    el = page.locator(f'#comment-{comment_id}')
                    if el.count() > 0:
                        el.first.scroll_into_view_if_needed()
                        time.sleep(0.3)
                        el.first.hover()
                        print(f"通过 #comment-{comment_id} 定位到评论(第 {attempt + 1} 次尝试)", file=sys.stderr)
                        return el.first
                except Exception:
                    pass
    
                # Priority 2: scan [data-user-id="{user_id}"]
                try:
                    user_comments = page.locator(f'[data-user-id="{reply_user_id}"]')
                    if user_comments.count() > 0:
                        for i in range(min(user_comments.count(), 20)):  # 限制单次扫描数量
                            try:
                                el = user_comments.nth(i)
                                el_id = el.get_attribute('id') or ''
                                el_data_cid = el.get_attribute('data-comment-id') or ''
                                if comment_id in el_id or comment_id in el_data_cid:
                                    el.scroll_into_view_if_needed()
                                    time.sleep(0.3)
                                    el.hover()
                                    print(f"通过 data-user-id 定位到评论(第 {attempt + 1} 次尝试)", file=sys.stderr)
                                    return el
                            except Exception:
                                continue
                except Exception:
                    pass
    
                # Scroll to trigger lazy-load of more comments
                page.evaluate("""() => {
                    const scroller = document.querySelector('.note-scroller') ||
                                      document.querySelector('.comments-wrap');
                    if (scroller) scroller.scrollTop += 500;
                }""")
                time.sleep(0.3)
    
                # Check comment count for growth (stagnation detection)
                try:
                    comments = page.locator('.comment-item')
                    current_count = comments.count()
                except Exception:
                    current_count = 0
    
                if current_count == last_comment_count:
                    stagnant += 1
                else:
                    stagnant = 0
                last_comment_count = current_count
    
                if stagnant >= 10:
                    # Check end-container to confirm no more items
                    if page.locator('.end-container').count() > 0:
                        print("检测到 end-container,停止滚动查找", file=sys.stderr)
                        break
                    # Safety: break after extended stagnation even without end-container
                    if stagnant >= 15:
                        print("评论列表长时间无增长,停止滚动查找", file=sys.stderr)
                        break
    
            print(f"未找到评论 {comment_id}(已滚动 {max_attempts} 次)", file=sys.stderr)
            return None
    
        def _type_and_submit(self, content: str, max_retries: int = 1) -> bool:
            """在评论输入框中输入文字并提交(人性化延迟 + 失败重试)"""
            for attempt in range(max_retries + 1):
                if attempt > 0:
                    print(f"重试 _type_and_submit(第 {attempt + 1}/{max_retries + 1} 次)...", file=sys.stderr)
                    time.sleep(random.uniform(2, 4))
    
                page = self.client.page
    
                # 点击评论输入框激活(span 占位符)
                try:
                    input_trigger = page.locator('div.input-box div.content-edit span')
                    input_trigger.first.click()
                    time.sleep(0.5)
                except Exception as e:
                    print(f"点击评论输入框失败: {e}", file=sys.stderr)
                    if attempt < max_retries:
                        continue
                    return False
    
                # 在 contenteditable 的 p 元素中输入文字(人性化随机延迟)
                try:
                    input_el = page.locator('div.input-box div.content-edit p.content-input')
                    input_el.first.click()
                    time.sleep(0.3)
                    typing_delay = random.randint(TYPING_DELAY_MIN, TYPING_DELAY_MAX)
                    page.keyboard.type(content, delay=typing_delay)
                    # 提交前随机等待,模拟人类检查
                    pre_wait = random.uniform(PRE_SUBMIT_DELAY_MIN, PRE_SUBMIT_DELAY_MAX)
                    time.sleep(pre_wait)
                except Exception as e:
                    print(f"输入评论内容失败: {e}", file=sys.stderr)
                    if attempt < max_retries:
                        continue
                    return False
    
                # 点击发送按钮
                try:
                    submit_btn = page.locator('div.bottom button.submit')
                    submit_btn.first.click()
                    time.sleep(1.5)
                except Exception as e:
                    print(f"点击发送按钮失败: {e}", file=sys.stderr)
                    if attempt < max_retries:
                        continue
                    return False
    
                # 检查是否触发频率限制
                if self._check_rate_limit():
                    return False
    
                return True
    
            return False
    
        def post_comment(
            self,
            feed_id: str,
            xsec_token: str,
            content: str,
        ) -> Dict[str, Any]:
            """
            发表评论
    
            Args:
                feed_id: 笔记 ID
                xsec_token: xsec_token
                content: 评论内容
    
            Returns:
                操作结果
            """
            # 评论内容校验
            error = self.validate_comment(content)
            if error:
                return {
                    "status": "error",
                    "feed_id": feed_id,
                    "content": content,
                    "message": error,
                }
    
            self._navigate_to_feed(feed_id, xsec_token)
    
            # 滚动到评论区域
            self.client.page.evaluate("""() => {
                const comments = document.querySelector('.comments-wrap') ||
                                  document.querySelector('.comment-wrapper');
                if (comments) comments.scrollIntoView();
            }""")
            time.sleep(1)
    
            success = self._type_and_submit(content)
    
            if success:
                print("评论发送成功", file=sys.stderr)
                # 提交后冷却(one-send-per-turn 理念)
                cooldown = random.uniform(POST_SUBMIT_COOLDOWN_MIN, POST_SUBMIT_COOLDOWN_MAX)
                print(f"提交后冷却 {cooldown:.1f}s...", file=sys.stderr)
                time.sleep(cooldown)
                return {
                    "status": "success",
                    "feed_id": feed_id,
                    "content": content,
                    "message": "评论发送成功",
                }
            else:
                return {
                    "status": "error",
                    "feed_id": feed_id,
                    "content": content,
                    "message": "评论发送失败",
                }
    
        def reply_to_comment(
            self,
            feed_id: str,
            xsec_token: str,
            comment_id: str,
            reply_user_id: str,
            content: str,
        ) -> Dict[str, Any]:
            """
            回复评论
    
            Args:
                feed_id: 笔记 ID
                xsec_token: xsec_token
                comment_id: 目标评论 ID
                reply_user_id: 被回复用户 ID
                content: 回复内容
    
            Returns:
                操作结果
            """
            # 评论内容校验
            error = self.validate_comment(content)
            if error:
                return {
                    "status": "error",
                    "feed_id": feed_id,
                    "comment_id": comment_id,
                    "content": content,
                    "message": error,
                }
    
            self._navigate_to_feed(feed_id, xsec_token)
    
            page = self.client.page
    
            # 滚动到评论区域
            page.evaluate("""() => {
                const comments = document.querySelector('.comments-wrap') ||
                                  document.querySelector('.comment-wrapper');
                if (comments) comments.scrollIntoView();
            }""")
            time.sleep(1)
    
            # 滚动查找目标评论(支持懒加载,从 Go comment_feed.go:157-273 移植)
            comment_el = self._find_comment_with_scroll(comment_id, reply_user_id)
    
            try:
                if comment_el is not None:
                    # 点击回复按钮
                    reply_btn = comment_el.locator('.reply-btn, button:has-text("回复"), span:has-text("回复")')
                    if reply_btn.count() > 0:
                        reply_btn.first.click()
                        time.sleep(0.5)
                        # 验证输入框 placeholder
                        self._verify_input_placeholder("回复")
                    else:
                        print("未找到回复按钮,尝试直接在评论框回复", file=sys.stderr)
                else:
                    print(f"未找到评论 {comment_id},尝试直接在评论框回复", file=sys.stderr)
            except Exception as e:
                print(f"定位目标评论失败: {e}", file=sys.stderr)
    
            # 输入回复内容并发送
            success = self._type_and_submit(content)
    
            if success:
                print("回复发送成功", file=sys.stderr)
                # 提交后冷却
                cooldown = random.uniform(POST_SUBMIT_COOLDOWN_MIN, POST_SUBMIT_COOLDOWN_MAX)
                print(f"提交后冷却 {cooldown:.1f}s...", file=sys.stderr)
                time.sleep(cooldown)
                return {
                    "status": "success",
                    "feed_id": feed_id,
                    "comment_id": comment_id,
                    "reply_user_id": reply_user_id,
                    "content": content,
                    "message": "回复发送成功",
                }
            else:
                return {
                    "status": "error",
                    "feed_id": feed_id,
                    "comment_id": comment_id,
                    "content": content,
                    "message": "回复发送失败",
                }
    
        def reply_via_notification(
            self,
            content: str,
            notification_index: int = 0,
        ) -> Dict[str, Any]:
            """
            通过通知页回复评论(比直跳详情页更安全)
    
            Flow:
            1. 导航到 /notification 通知页
            2. 定位目标通知项
            3. 点击回复
            4. 输入内容并提交
    
            Args:
                content: 回复内容
                notification_index: 通知项索引(0 = 最新)
    
            Returns:
                操作结果
            """
            # 评论内容校验
            error = self.validate_comment(content)
            if error:
                return {"status": "error", "message": error}
    
            page = self.client.page
            print("导航到通知页...", file=sys.stderr)
            self.client.navigate("https://www.xiaohongshu.com/notification")
            time.sleep(3)
    
            # 查找通知项
            notifications = page.locator('.notification-item, .notify-item, .message-item')
            total = notifications.count()
            if total <= notification_index:
                return {
                    "status": "error",
                    "message": f"通知项索引超出范围(索引 {notification_index},共 {total} 条)",
                }
    
            target = notifications.nth(notification_index)
            target.hover()
            time.sleep(0.5)
    
            # 点击回复按钮
            reply_btn = target.locator('span:has-text("回复"), button:has-text("回复")')
            if reply_btn.count() > 0:
                reply_btn.first.click()
                time.sleep(1)
                # 验证输入框 placeholder
                self._verify_input_placeholder("回复")
            else:
                # 回退:直接点击通知项
                target.click()
                time.sleep(2)
    
            # 输入并提交
            success = self._type_and_submit(content)
    
            if success:
                print("通知页回复成功", file=sys.stderr)
                cooldown = random.uniform(POST_SUBMIT_COOLDOWN_MIN, POST_SUBMIT_COOLDOWN_MAX)
                print(f"提交后冷却 {cooldown:.1f}s...", file=sys.stderr)
                time.sleep(cooldown)
                return {
                    "status": "success",
                    "action": "reply_notification",
                    "notification_index": notification_index,
                    "content": content,
                    "message": "通知页回复成功",
                }
            else:
                return {
                    "status": "error",
                    "action": "reply_notification",
                    "notification_index": notification_index,
                    "content": content,
                    "message": "通知页回复失败",
                }
    
    
    def post_comment(
        feed_id: str,
        xsec_token: str,
        content: str,
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
    ) -> Dict[str, Any]:
        """
        发表评论
    
        Args:
            feed_id: 笔记 ID
            xsec_token: xsec_token
            content: 评论内容
            headless: 是否无头模式
            cookie_path: Cookie 路径
    
        Returns:
            操作结果
        """
        client = XiaohongshuClient(
            headless=headless,
            cookie_path=cookie_path,
        )
    
        try:
            client.start()
            action = CommentAction(client)
            return action.post_comment(feed_id, xsec_token, content)
        finally:
            client.close()
    
    
    def reply_to_comment(
        feed_id: str,
        xsec_token: str,
        comment_id: str,
        reply_user_id: str,
        content: str,
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
    ) -> Dict[str, Any]:
        """
        回复评论
    
        Args:
            feed_id: 笔记 ID
            xsec_token: xsec_token
            comment_id: 目标评论 ID
            reply_user_id: 被回复用户 ID
            content: 回复内容
            headless: 是否无头模式
            cookie_path: Cookie 路径
    
        Returns:
            操作结果
        """
        client = XiaohongshuClient(
            headless=headless,
            cookie_path=cookie_path,
        )
    
        try:
            client.start()
            action = CommentAction(client)
            return action.reply_to_comment(
                feed_id, xsec_token, comment_id, reply_user_id, content
            )
        finally:
            client.close()
    
    
    def reply_via_notification(
        content: str,
        notification_index: int = 0,
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
    ) -> Dict[str, Any]:
        """
        通过通知页回复评论(安全路径)
    
        Args:
            content: 回复内容
            notification_index: 通知项索引(0 = 最新)
            headless: 是否无头模式
            cookie_path: Cookie 路径
    
        Returns:
            操作结果
        """
        client = XiaohongshuClient(
            headless=headless,
            cookie_path=cookie_path,
        )
    
        try:
            client.start()
            action = CommentAction(client)
            return action.reply_via_notification(content, notification_index)
        finally:
            client.close()
    
  • scripts/docs_check.py3.9 KB0e0ea790738cupstream ↗
    """
    Public documentation checks.
    
    The checks are intentionally small. They catch private local paths, common
    secret shapes, and a short list of writing patterns we do not want in public
    project docs.
    """
    
    from __future__ import annotations
    
    import argparse
    import re
    import sys
    from dataclasses import dataclass
    from pathlib import Path
    from typing import Iterable
    
    DEFAULT_TARGETS = [
        "README.md",
        "README_EN.md",
        "SKILL.md",
        "AGENTS.md",
        "CONTRIBUTING.md",
        "CHANGELOG.md",
        "docs",
        "examples",
        ".github",
        "site",
    ]
    
    PUBLIC_SUFFIXES = {".md", ".html", ".txt", ".xml", ".svg", ".json"}
    
    PRIVACY_PATTERNS = [
        re.compile(r"C:\\+Users\\+", re.IGNORECASE),
        re.compile(r"D:\\+Code\\+", re.IGNORECASE),
        re.compile(r"/Users/[^/\s]+"),
        re.compile(r"cookies?\.json", re.IGNORECASE),
        re.compile(r"browser-data", re.IGNORECASE),
        re.compile(r"\.secret", re.IGNORECASE),
        re.compile(r"password", re.IGNORECASE),
        re.compile(r"手机号"),
        re.compile(r"AKIA[0-9A-Z]{16}"),
        re.compile(r"sk-[A-Za-z0-9]{16,}"),
    ]
    
    WRITING_PATTERNS = [
        re.compile(r"—"),
        re.compile(r"\bdelve\b", re.IGNORECASE),
        re.compile(r"\bleverage\b", re.IGNORECASE),
        re.compile(r"\brobust\b", re.IGNORECASE),
        re.compile(r"\bcomprehensive\b", re.IGNORECASE),
        re.compile(r"\bseamless\b", re.IGNORECASE),
        re.compile(r"\bgame[- ]changer\b", re.IGNORECASE),
        re.compile(r"\bimpactful\b", re.IGNORECASE),
        re.compile(r"\bactionable\b", re.IGNORECASE),
        re.compile(r"\bworth noting\b", re.IGNORECASE),
        re.compile(r"\bimportant to note\b", re.IGNORECASE),
        re.compile(r"\bat its core\b", re.IGNORECASE),
        re.compile(r"\bbest practices\b", re.IGNORECASE),
        re.compile(r"\bserves as\b", re.IGNORECASE),
        re.compile(r"落地|闭环|抓手|赋能|沉淀|证据链|证据矩阵"),
    ]
    
    
    @dataclass(frozen=True)
    class Finding:
        path: Path
        line: int
        kind: str
        text: str
    
    
    def iter_public_files(targets: Iterable[Path]) -> list[Path]:
        files: list[Path] = []
        for target in targets:
            if not target.exists():
                continue
            if target.is_file() and target.suffix.lower() in PUBLIC_SUFFIXES:
                files.append(target)
            elif target.is_dir():
                files.extend(
                    path for path in target.rglob("*")
                    if path.is_file()
                    and path.suffix.lower() in PUBLIC_SUFFIXES
                    and ".git" not in path.parts
                    and "__pycache__" not in path.parts
                )
        return sorted(set(files))
    
    
    def _matches(line_text: str, patterns: Iterable[re.Pattern[str]]) -> bool:
        return any(pattern.search(line_text) for pattern in patterns)
    
    
    def scan_files(files: Iterable[Path]) -> list[Finding]:
        findings: list[Finding] = []
        for path in files:
            try:
                lines = path.read_text(encoding="utf-8").splitlines()
            except UnicodeDecodeError:
                lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
    
            for index, line_text in enumerate(lines, start=1):
                if _matches(line_text, PRIVACY_PATTERNS):
                    findings.append(Finding(path=path, line=index, kind="privacy", text=line_text.strip()))
                if _matches(line_text, WRITING_PATTERNS):
                    findings.append(Finding(path=path, line=index, kind="writing", text=line_text.strip()))
        return findings
    
    
    def main(argv: list[str] | None = None) -> int:
        parser = argparse.ArgumentParser(description="Check public docs for private data and writing issues.")
        parser.add_argument("paths", nargs="*", default=DEFAULT_TARGETS, help="Files or directories to scan.")
        args = parser.parse_args(argv)
    
        files = iter_public_files([Path(path) for path in args.paths])
        findings = scan_files(files)
        for finding in findings:
            print(f"{finding.path}:{finding.line}: {finding.kind}: {finding.text}")
    
        return 1 if findings else 0
    
    
    if __name__ == "__main__":
        sys.exit(main())
    
  • scripts/explore.py4.5 KB83a85d2cdafbupstream ↗
    """
    小红书首页推荐流模块
    
    Reference: xiaohongshu-mcp/feeds.go (Apache-2.0). See THIRD_PARTY_NOTICES.md.
    """
    
    import json
    import sys
    import time
    from typing import Any, Dict, List
    
    from .client import DEFAULT_COOKIE_PATH, XiaohongshuClient
    
    
    class ExploreAction:
        """首页推荐流动作"""
    
        EXPLORE_URL = "https://www.xiaohongshu.com/explore"
    
        def __init__(self, client: XiaohongshuClient):
            self.client = client
    
        def _extract_feeds(self) -> List[Dict[str, Any]]:
            """从 __INITIAL_STATE__ 提取首页推荐笔记列表"""
            page = self.client.page
    
            result = page.evaluate("""() => {
                var s = window.__INITIAL_STATE__;
                if (!s || !s.feed || !s.feed.feeds) return '';
    
                var feeds = s.feed.feeds;
                var data = feeds;
                if (feeds.value !== undefined) data = feeds.value;
                else if (feeds._value !== undefined) data = feeds._value;
    
                if (!data || !Array.isArray(data)) return '';
    
                // 展平二维数组(如果有的话)
                var flat = [];
                for (var i = 0; i < data.length; i++) {
                    if (Array.isArray(data[i])) {
                        for (var j = 0; j < data[i].length; j++) flat.push(data[i][j]);
                    } else {
                        flat.push(data[i]);
                    }
                }
    
                // 提取每条笔记的关键信息
                return JSON.stringify(flat.map(function(item) {
                    var nc = item.noteCard || (item.model_type === 'note' ? item : {});
                    if (item.noteCard) nc = item.noteCard;
                    var info = nc.interactInfo || {};
                    var user = nc.user || {};
                    var cover = nc.cover || {};
                    return {
                        id: item.id || '',
                        xsecToken: item.xsecToken || '',
                        noteCard: {
                            displayTitle: nc.displayTitle || nc.title || '',
                            type: nc.type || '',
                            interactInfo: {
                                likedCount: info.likedCount || '0',
                                collectedCount: info.collectedCount || '0',
                                commentCount: info.commentCount || '0',
                                sharedCount: info.sharedCount || '0'
                            },
                            user: {
                                nickname: user.nickname || user.nickName || '',
                                userId: user.userId || ''
                            },
                            cover: {
                                urlDefault: cover.urlDefault || cover.urlPre || ''
                            }
                        }
                    };
                }));
            }""")
    
            if not result:
                return []
    
            try:
                return json.loads(result)
            except json.JSONDecodeError:
                return []
    
        def get_feeds(self, limit: int = 20) -> Dict[str, Any]:
            """
            获取首页推荐流
    
            Args:
                limit: 最大返回数量
    
            Returns:
                推荐笔记列表
            """
            client = self.client
    
            print("打开首页推荐流...", file=sys.stderr)
            client.navigate(self.EXPLORE_URL)
            client.wait_for_initial_state()
            time.sleep(2)
    
            feeds = self._extract_feeds()
    
            # 如果首页数据较少,尝试滚动加载更多
            if len(feeds) < limit:
                for _ in range(3):
                    client.scroll_to_bottom(800)
                    time.sleep(1.5)
                    new_feeds = self._extract_feeds()
                    if len(new_feeds) > len(feeds):
                        feeds = new_feeds
                    if len(feeds) >= limit:
                        break
    
            # 截取到 limit
            feeds = feeds[:limit]
    
            print(f"获取到 {len(feeds)} 条推荐笔记", file=sys.stderr)
            return {
                "count": len(feeds),
                "feeds": feeds,
            }
    
    
    def explore(
        limit: int = 20,
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
    ) -> Dict[str, Any]:
        """
        获取首页推荐流
    
        Args:
            limit: 最大返回数量
            headless: 是否无头模式
            cookie_path: Cookie 路径
    
        Returns:
            推荐笔记列表
        """
        client = XiaohongshuClient(
            headless=headless,
            cookie_path=cookie_path,
        )
    
        try:
            client.start()
            action = ExploreAction(client)
            return action.get_feeds(limit=limit)
        finally:
            client.close()
    
  • scripts/feed.py8.1 KB2d28234aaab1upstream ↗
    """
    小红书笔记详情模块
    
    Reference: xiaohongshu-mcp/feed_detail.go (Apache-2.0). See THIRD_PARTY_NOTICES.md.
    """
    
    import json
    import random
    import sys
    import time
    from typing import Any, Dict, Optional
    
    from ._utils import make_feed_url
    from .client import DEFAULT_COOKIE_PATH, XiaohongshuClient
    
    
    class FeedDetailAction:
        """笔记详情动作"""
    
        def __init__(self, client: XiaohongshuClient):
            self.client = client
    
        def _make_feed_detail_url(self, feed_id: str, xsec_token: str, xsec_source: str = "pc_feed") -> str:
            """构建笔记详情 URL(委托给 _utils.make_feed_url)"""
            return make_feed_url(feed_id, xsec_token, xsec_source)
    
        def _scroll_to_comments(self):
            """滚动到评论区域"""
            self.client.page.evaluate("""() => {
                const comments = document.querySelector('.comments-wrap');
                if (comments) {
                    comments.scrollIntoView();
                }
            }""")
            time.sleep(0.5)
    
        def _check_page_accessible(self):
            """检查页面是否可访问(笔记是否被删/私密/违规)"""
            page = self.client.page
            keywords = [
                "当前笔记暂时无法浏览", "该内容因违规已被删除", "该笔记已被删除",
                "内容不存在", "笔记不存在", "已失效", "私密笔记", "仅作者可见",
                "因用户设置你无法查看", "因违规无法查看"
            ]
            for kw in keywords:
                if page.locator(f"text={kw}").count() > 0:
                    raise Exception(f"笔记不可访问: {kw}")
            # Also check selectors
            for sel in [".access-wrapper", ".error-wrapper", ".not-found-wrapper", ".blocked-wrapper"]:
                if page.locator(sel).count() > 0:
                    raise Exception(f"笔记不可访问(检测到 {sel})")
    
        def _human_scroll(self, speed="normal", direction="down"):
            """模拟人类滚动(从 Go feed_detail.go:469-517 移植)"""
            page = self.client.page
            viewport = page.evaluate("() => window.innerHeight")
            ratios = {"slow": 0.5, "normal": 0.7, "fast": 0.9}
            ratio = ratios.get(speed, 0.7)
            jitter = random.randint(-50, 50)
            delta = int(viewport * ratio * (0.7 + random.random() * 0.2)) + jitter
            if direction == "up":
                delta = -delta
            page.evaluate(f"window.scrollBy({{top: {delta}, behavior: 'smooth'}})")
    
        def _smart_scroll(self):
            """smartScroll:调度 WheelEvent 到 .note-scroller(从 Go feed_detail.go:553-569 移植)"""
            self.client.page.evaluate("""() => {
                const scroller = document.querySelector('.note-scroller');
                if (scroller) {
                    scroller.dispatchEvent(new WheelEvent('wheel', {
                        deltaY: 200, deltaMode: 0, bubbles: true, cancelable: true
                    }));
                }
            }""")
    
        def _load_comments(self, max_items: int = 0):
            """
            加载评论(滚动 + 点击加载更多)
    
            Args:
                max_items: 最大评论数量,0 表示全部
            """
            page = self.client.page
    
            # 滚动到评论区域
            self._scroll_to_comments()
    
            # 随机延迟,模拟人类行为
            def human_delay():
                time.sleep(random.uniform(0.3, 0.7))
    
            max_attempts = 50 if max_items == 0 else max_items * 3
            last_count = 0
            stagnant = 0
    
            for attempt in range(max_attempts):
                # 检查是否有"加载更多"按钮
                try:
                    more_btn = page.locator('.more-comments')
                    if more_btn.is_visible():
                        more_btn.click()
                        human_delay()
                except Exception:
                    pass
    
                # 滚动:先 smartScroll(WheelEvent),再 humanScroll
                self._smart_scroll()
                human_delay()
                self._human_scroll()
                human_delay()
    
                # 获取当前评论数量
                try:
                    comments = page.locator('.comment-item')
                    current_count = comments.count()
                except Exception:
                    current_count = 0
    
                if current_count == last_count:
                    stagnant += 1
                    if stagnant >= 5:
                        break
                else:
                    stagnant = 0
    
                last_count = current_count
    
                # 检查是否达到目标数量
                if max_items > 0 and current_count >= max_items:
                    break
    
        def _extract_feed_detail(self, feed_id: str) -> Optional[Dict[str, Any]]:
            """提取笔记详情数据"""
            page = self.client.page
    
            # 检查页面是否可访问
            self._check_page_accessible()
    
            # 传入 feed_id,只提取对应条目,避免序列化整个 Vue Reactive 代理
            result = page.evaluate("""(fid) => {
                var s = window.__INITIAL_STATE__;
                if (!s || !s.note || !s.note.noteDetailMap) return '';
    
                var ndm = s.note.noteDetailMap;
                var map = ndm;
                if (ndm.value !== undefined) map = ndm.value;
                else if (ndm._value !== undefined) map = ndm._value;
    
                var detail = map[fid];
                if (!detail) return '';
    
                return JSON.stringify(detail);
            }""", feed_id)
    
            if not result:
                return None
    
            try:
                return json.loads(result)
            except json.JSONDecodeError:
                return None
    
        def get_feed_detail(
            self,
            feed_id: str,
            xsec_token: str,
            load_comments: bool = False,
            max_comments: int = 0,
            xsec_source: str = "pc_feed",
        ) -> Optional[Dict[str, Any]]:
            """
            获取笔记详情
    
            Args:
                feed_id: 笔记 ID
                xsec_token: xsec_token 参数
                load_comments: 是否加载评论
                max_comments: 最大评论数量,0 表示全部
                xsec_source: 来源标识(pc_feed/pc_note/pc_search)
    
            Returns:
                笔记详情数据
            """
            client = self.client
    
            # 构建 URL 并导航
            url = self._make_feed_detail_url(feed_id, xsec_token, xsec_source)
            print(f"打开笔记详情页: {url}", file=sys.stderr)
            client.navigate(url)
    
            # 等待页面加载
            client.wait_for_initial_state()
            time.sleep(2)
    
            # 重试提取:noteDetailMap 可能需要额外时间填充
            detail = None
            for attempt in range(3):
                detail = self._extract_feed_detail(feed_id)
                if detail:
                    break
                if attempt < 2:
                    print(f"noteDetailMap 未就绪,等待重试 ({attempt + 1}/3)...", file=sys.stderr)
                    time.sleep(2)
    
            # 加载评论
            if detail and load_comments:
                print("加载评论中...", file=sys.stderr)
                self._load_comments(max_comments)
                # 重新提取以包含评论数据
                detail = self._extract_feed_detail(feed_id) or detail
    
            if not detail:
                print("未获取到笔记详情", file=sys.stderr)
                return None
    
            return detail
    
    
    def feed_detail(
        feed_id: str,
        xsec_token: str,
        load_comments: bool = False,
        max_comments: int = 0,
        xsec_source: str = "pc_feed",
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
    ) -> Optional[Dict[str, Any]]:
        """
        获取笔记详情
    
        Args:
            feed_id: 笔记 ID
            xsec_token: xsec_token 参数
            load_comments: 是否加载评论
            max_comments: 最大评论数量
            xsec_source: 来源标识
            headless: 是否无头模式
            cookie_path: Cookie 路径
    
        Returns:
            笔记详情数据
        """
        client = XiaohongshuClient(
            headless=headless,
            cookie_path=cookie_path,
        )
    
        try:
            client.start()
            action = FeedDetailAction(client)
            return action.get_feed_detail(
                feed_id=feed_id,
                xsec_token=xsec_token,
                load_comments=load_comments,
                max_comments=max_comments,
                xsec_source=xsec_source,
            )
        finally:
            client.close()
    
  • scripts/interact.py11 KBbe6d8c6cc796upstream ↗
    """
    小红书互动模块(点赞 / 取消点赞 / 收藏 / 取消收藏)
    
    Reference: xiaohongshu-mcp/like_favorite.go (Apache-2.0). See THIRD_PARTY_NOTICES.md.
    安全互动校验:人性化延迟、频率检测、批次冷却
    """
    
    import json
    import random
    import sys
    import time
    from typing import Any, Dict
    
    from ._utils import make_feed_url
    from .client import DEFAULT_COOKIE_PATH, XiaohongshuClient
    from .selectors import (
        INTERACT_COLLECT_ACTIVE_CONTRACT,
        INTERACT_COLLECT_BUTTON_CONTRACT,
        INTERACT_LIKE_ACTIVE_CONTRACT,
        INTERACT_LIKE_BUTTON_CONTRACT,
        INTERACT_RATE_LIMIT_TOAST_CONTRACT,
    )
    
    # 互动安全常量
    PRE_CLICK_DELAY_MIN = 1.0     # 点击前延迟下限(秒)
    PRE_CLICK_DELAY_MAX = 2.5     # 点击前延迟上限(秒)
    POST_CLICK_COOLDOWN_MIN = 5   # 点击后冷却下限(秒)
    POST_CLICK_COOLDOWN_MAX = 12  # 点击后冷却上限(秒)
    BATCH_INTERACT_THRESHOLD = 3  # 连续交互触发批次冷却的阈值
    BATCH_COOLDOWN_MIN = 15       # 批次冷却下限(秒)
    BATCH_COOLDOWN_MAX = 30       # 批次冷却上限(秒)
    
    
    class InteractAction:
        """互动动作(点赞、收藏)"""
    
        # CSS 选择器(兼容常量从契约派生,契约是唯一事实源)
        LIKE_SELECTOR = INTERACT_LIKE_BUTTON_CONTRACT.primary
        LIKE_ACTIVE_SELECTOR = INTERACT_LIKE_ACTIVE_CONTRACT.primary
        COLLECT_SELECTOR = INTERACT_COLLECT_BUTTON_CONTRACT.primary
        COLLECT_ACTIVE_SELECTOR = INTERACT_COLLECT_ACTIVE_CONTRACT.primary
        RATE_LIMIT_SELECTORS = INTERACT_RATE_LIMIT_TOAST_CONTRACT.selectors
    
        def __init__(self, client: XiaohongshuClient):
            self.client = client
            self._interact_count = 0  # 交互计数(用于批次冷却)
    
        def _make_feed_url(self, feed_id: str, xsec_token: str, xsec_source: str = "pc_feed") -> str:
            """构建笔记详情 URL(委托给 _utils.make_feed_url)"""
            return make_feed_url(feed_id, xsec_token, xsec_source)
    
        def _navigate_to_feed(self, feed_id: str, xsec_token: str):
            """导航到笔记详情页并等待加载"""
            url = self._make_feed_url(feed_id, xsec_token)
            print(f"打开笔记详情页: {url}", file=sys.stderr)
            self.client.navigate(url)
            self.client.wait_for_initial_state()
            time.sleep(2)
    
        def _get_interact_state(self, feed_id: str) -> Dict[str, bool]:
            """
            从 __INITIAL_STATE__ 获取当前互动状态
    
            Returns:
                {"liked": bool, "collected": bool}
            """
            page = self.client.page
            result = page.evaluate("""(fid) => {
                var s = window.__INITIAL_STATE__;
                if (!s || !s.note || !s.note.noteDetailMap) return '';
    
                var ndm = s.note.noteDetailMap;
                var map = ndm;
                if (ndm.value !== undefined) map = ndm.value;
                else if (ndm._value !== undefined) map = ndm._value;
    
                var detail = map[fid];
                if (!detail || !detail.note || !detail.note.interactInfo) return '';
    
                var info = detail.note.interactInfo;
                return JSON.stringify({
                    liked: !!info.liked,
                    collected: !!info.collected
                });
            }""", feed_id)
    
            if not result:
                return {"liked": False, "collected": False}
    
            try:
                return json.loads(result)
            except json.JSONDecodeError:
                return {"liked": False, "collected": False}
    
        def _click_button(self, selector: str, label: str) -> bool:
            """点击互动按钮"""
            page = self.client.page
            try:
                btn = page.locator(selector)
                if btn.count() > 0:
                    btn.first.click()
                    time.sleep(1.5)
                    return True
                else:
                    print(f"未找到{label}按钮: {selector}", file=sys.stderr)
                    return False
            except Exception as e:
                print(f"点击{label}按钮失败: {e}", file=sys.stderr)
                return False
    
        def _check_rate_limit(self) -> bool:
            """
            检测是否触发了互动频率限制
    
            Returns:
                True 表示被限流
            """
            page = self.client.page
            try:
                for sel in self.RATE_LIMIT_SELECTORS:
                    toast = page.locator(sel)
                    if toast.count() > 0 and toast.first.is_visible():
                        toast_text = toast.first.text_content()
                        print(f"检测到频率限制: {toast_text}", file=sys.stderr)
                        return True
            except Exception:
                pass
            return False
    
        def _humanized_interact(self, selector: str, label: str) -> bool:
            """
            人性化互动:点击前随机延迟 → 点击 → 频率检测 → 批次冷却
    
            Args:
                selector: 按钮 CSS 选择器
                label: 操作标签(用于日志)
    
            Returns:
                True 表示操作成功
            """
            # 点击前随机延迟
            pre_delay = random.uniform(PRE_CLICK_DELAY_MIN, PRE_CLICK_DELAY_MAX)
            time.sleep(pre_delay)
    
            success = self._click_button(selector, label)
    
            if success:
                # 检查频率限制
                if self._check_rate_limit():
                    print(f"{label}后检测到频率限制", file=sys.stderr)
                    return False
    
                self._interact_count += 1
    
                # 批次冷却
                if self._interact_count % BATCH_INTERACT_THRESHOLD == 0:
                    cooldown = random.uniform(BATCH_COOLDOWN_MIN, BATCH_COOLDOWN_MAX)
                    print(f"批次冷却(第 {self._interact_count} 次交互): {cooldown:.1f}s", file=sys.stderr)
                    time.sleep(cooldown)
                else:
                    # 普通冷却
                    cooldown = random.uniform(POST_CLICK_COOLDOWN_MIN, POST_CLICK_COOLDOWN_MAX)
                    time.sleep(cooldown)
    
            return success
    
        def like(self, feed_id: str, xsec_token: str) -> Dict[str, Any]:
            """
            点赞笔记
    
            Returns:
                操作结果
            """
            self._navigate_to_feed(feed_id, xsec_token)
    
            state = self._get_interact_state(feed_id)
            if state.get("liked"):
                return {
                    "status": "success",
                    "action": "like",
                    "feed_id": feed_id,
                    "already_liked": True,
                    "message": "已经点赞过了",
                }
    
            success = self._humanized_interact(self.LIKE_SELECTOR, "点赞")
            return {
                "status": "success" if success else "error",
                "action": "like",
                "feed_id": feed_id,
                "message": "点赞成功" if success else "点赞失败",
            }
    
        def unlike(self, feed_id: str, xsec_token: str) -> Dict[str, Any]:
            """
            取消点赞
    
            Returns:
                操作结果
            """
            self._navigate_to_feed(feed_id, xsec_token)
    
            state = self._get_interact_state(feed_id)
            if not state.get("liked"):
                return {
                    "status": "success",
                    "action": "unlike",
                    "feed_id": feed_id,
                    "already_unliked": True,
                    "message": "尚未点赞,无需取消",
                }
    
            success = self._humanized_interact(self.LIKE_SELECTOR, "取消点赞")
            return {
                "status": "success" if success else "error",
                "action": "unlike",
                "feed_id": feed_id,
                "message": "取消点赞成功" if success else "取消点赞失败",
            }
    
        def collect(self, feed_id: str, xsec_token: str) -> Dict[str, Any]:
            """
            收藏笔记
    
            Returns:
                操作结果
            """
            self._navigate_to_feed(feed_id, xsec_token)
    
            state = self._get_interact_state(feed_id)
            if state.get("collected"):
                return {
                    "status": "success",
                    "action": "collect",
                    "feed_id": feed_id,
                    "already_collected": True,
                    "message": "已经收藏过了",
                }
    
            success = self._humanized_interact(self.COLLECT_SELECTOR, "收藏")
            return {
                "status": "success" if success else "error",
                "action": "collect",
                "feed_id": feed_id,
                "message": "收藏成功" if success else "收藏失败",
            }
    
        def uncollect(self, feed_id: str, xsec_token: str) -> Dict[str, Any]:
            """
            取消收藏
    
            Returns:
                操作结果
            """
            self._navigate_to_feed(feed_id, xsec_token)
    
            state = self._get_interact_state(feed_id)
            if not state.get("collected"):
                return {
                    "status": "success",
                    "action": "uncollect",
                    "feed_id": feed_id,
                    "already_uncollected": True,
                    "message": "尚未收藏,无需取消",
                }
    
            success = self._humanized_interact(self.COLLECT_SELECTOR, "取消收藏")
            return {
                "status": "success" if success else "error",
                "action": "uncollect",
                "feed_id": feed_id,
                "message": "取消收藏成功" if success else "取消收藏失败",
            }
    
    
    # ============================================================
    # 便捷函数
    # ============================================================
    
    def _run_interact(action_name: str, feed_id: str, xsec_token: str,
                      headless: bool = True, cookie_path: str = DEFAULT_COOKIE_PATH) -> Dict[str, Any]:
        """通用互动操作执行器"""
        client = XiaohongshuClient(headless=headless, cookie_path=cookie_path)
        try:
            client.start()
            action = InteractAction(client)
            method = getattr(action, action_name)
            return method(feed_id, xsec_token)
        finally:
            client.close()
    
    
    def like(feed_id: str, xsec_token: str, headless: bool = True,
             cookie_path: str = DEFAULT_COOKIE_PATH) -> Dict[str, Any]:
        """点赞笔记"""
        return _run_interact("like", feed_id, xsec_token, headless, cookie_path)
    
    
    def unlike(feed_id: str, xsec_token: str, headless: bool = True,
               cookie_path: str = DEFAULT_COOKIE_PATH) -> Dict[str, Any]:
        """取消点赞"""
        return _run_interact("unlike", feed_id, xsec_token, headless, cookie_path)
    
    
    def collect(feed_id: str, xsec_token: str, headless: bool = True,
                cookie_path: str = DEFAULT_COOKIE_PATH) -> Dict[str, Any]:
        """收藏笔记"""
        return _run_interact("collect", feed_id, xsec_token, headless, cookie_path)
    
    
    def uncollect(feed_id: str, xsec_token: str, headless: bool = True,
                  cookie_path: str = DEFAULT_COOKIE_PATH) -> Dict[str, Any]:
        """取消收藏"""
        return _run_interact("uncollect", feed_id, xsec_token, headless, cookie_path)
    
  • scripts/login.py11 KBecf8584acd18upstream ↗
    """
    小红书登录模块
    
    Reference: xiaohongshu-mcp/login.go (Apache-2.0). See THIRD_PARTY_NOTICES.md.
    支持生成微信登录二维码,保存供主模型发送
    """
    
    import base64
    import os
    import sys
    import time
    from typing import Any, Dict, Optional, Tuple
    
    from .client import DEFAULT_COOKIE_PATH, XiaohongshuClient
    from .profiles import env_profile, profile_paths
    from .selectors import (
        LOGIN_CREATOR_READY_CONTRACT,
        LOGIN_PROFILE_LINK_CONTRACT,
        LOGIN_QRCODE_CONTRACT,
    )
    
    # QRCode 图片保存目录 - 放在 skill 文件夹内
    SKILL_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    QRCODE_DIR = os.path.join(SKILL_DIR, "data")
    QRCODE_PATH = os.path.join(QRCODE_DIR, "qrcode.png")
    
    # Creator Center login and publish detection.
    CREATOR_PUBLISH_URL = "https://creator.xiaohongshu.com/publish/publish?source=official"
    CREATOR_AUTH_URL_MARKERS = ("/login", "/captcha", "verify")
    MAIN_PROFILE_SELECTOR = LOGIN_PROFILE_LINK_CONTRACT.primary
    
    
    class LoginAction:
        """登录动作"""
    
        QRCODE_SELECTOR = LOGIN_QRCODE_CONTRACT.primary
        PROFILE_LINK_SELECTOR = LOGIN_PROFILE_LINK_CONTRACT.primary
        CREATOR_READY_SELECTORS = LOGIN_CREATOR_READY_CONTRACT.selectors
    
        def __init__(self, client: XiaohongshuClient):
            self.client = client
    
        def check_login_status(self, navigate: bool = True) -> Tuple[bool, Optional[str]]:
            """Return whether the account is logged in from live page state."""
            page = self.client.page
    
            if navigate:
                self.client.navigate("https://www.xiaohongshu.com/explore")
                time.sleep(3)
    
            # QR modal visible -> logged out
            qr = page.locator(self.QRCODE_SELECTOR)
            if qr.count() > 0 and qr.first.is_visible():
                return False, None
    
            # Sidebar profile link visible -> logged in
            profile_link = page.locator(self.PROFILE_LINK_SELECTOR)
            if profile_link.count() > 0 and profile_link.first.is_visible():
                return True, "已登录用户"
    
            return False, None
    
        def check_creator_login_status(self, navigate: bool = True) -> bool:
            """Return whether the Creator Center shows an authenticated page."""
            if navigate:
                self.client.navigate(CREATOR_PUBLISH_URL)
                time.sleep(3)
    
            if self._is_creator_auth_page():
                return False
    
            if self._any_creator_ready_visible():
                return True
    
            url = (self.client.page.url or "").lower()
            return url.startswith("https://creator.xiaohongshu.com")
    
        def _is_creator_auth_page(self) -> bool:
            """Return True when still on the Creator Center login or captcha page."""
            url = (self.client.page.url or "").lower()
            return any(marker in url for marker in CREATOR_AUTH_URL_MARKERS)
    
        def _any_creator_ready_visible(self) -> bool:
            """Return True when any Creator Center ready candidate is visible."""
            page = self.client.page
            for selector in self.CREATOR_READY_SELECTORS:
                try:
                    loc = page.locator(selector)
                    if loc.count() > 0 and loc.first.is_visible():
                        return True
                except Exception:
                    continue
            return False
    
        def wait_for_creator_login(self, timeout: int = 240) -> bool:
            """Wait for the user to complete Creator Center login in a browser."""
            deadline = time.time() + timeout
            while time.time() < deadline:
                if self.check_creator_login_status(navigate=False):
                    self.client._save_cookies()
                    return True
                time.sleep(2)
            return False
    
        def get_wechat_qrcode(self) -> Tuple[Optional[str], bool]:
            """
            获取微信登录二维码
    
            流程:
            1. 访问小红书首页触发登录弹窗
            2. 获取弹窗中的微信二维码图片
            3. 保存到文件
    
            Returns:
                (二维码文件路径, 是否已登录)
            """
            client = self.client
            page = client.page
    
            # 访问首页触发登录弹窗
            client.navigate("https://www.xiaohongshu.com/explore")
            time.sleep(4)  # 给弹窗足够时间渲染
    
            # 先检查是否已登录(不要重新 navigate)
            is_logged_in, _ = self.check_login_status(navigate=False)
            if is_logged_in:
                return None, True
    
            # 尝试获取二维码 base64 图片
            qrcode_src = None
            for attempt in range(5):
                try:
                    qr = page.locator(self.QRCODE_SELECTOR)
                    if qr.count() > 0:
                        src = qr.first.get_attribute('src')
                        if src and len(src) > 200:  # 有效 base64 至少上百字符
                            qrcode_src = src
                            break
                except Exception:
                    pass
                time.sleep(1)
    
            if qrcode_src:
                # 去掉 data:image/png;base64, 前缀
                if ',' in qrcode_src:
                    qrcode_src = qrcode_src.split(',', 1)[1]
    
                # 保存二维码图片
                img_data = base64.b64decode(qrcode_src)
                os.makedirs(QRCODE_DIR, exist_ok=True)
                with open(QRCODE_PATH, 'wb') as f:
                    f.write(img_data)
    
                print(f"二维码已保存到: {QRCODE_PATH}", file=sys.stderr)
                return QRCODE_PATH, False
    
            # 后备:整页截屏
            print("未找到有效的二维码图片,截屏保存...", file=sys.stderr)
            os.makedirs(QRCODE_DIR, exist_ok=True)
            page.screenshot(path=QRCODE_PATH)
            return QRCODE_PATH, False
    
        def wait_for_login(self, timeout: int = 120, min_wait: int = 30) -> bool:
            """
            在 **当前页面** 上等待用户扫码登录。
            不会重新 navigate,以免刷新掉二维码弹窗。
    
            会强制等待至少 min_wait 秒再开始检测,
            给用户足够时间在手机上确认登录。
    
            Args:
                timeout: 总超时时间(秒)
                min_wait: 最少等待秒数(默认 30)
    
            Returns:
                是否登录成功
            """
            start = time.time()
    
            # ---- 阶段 1: 强制等待 min_wait 秒 ----
            print(f"请在手机上扫码并确认登录(至少等待 {min_wait} 秒)...", file=sys.stderr)
            while time.time() - start < min_wait:
                elapsed = int(time.time() - start)
                remaining = min_wait - elapsed
                if remaining > 0 and remaining % 10 == 0:
                    print(f"  等待中... 还剩 {remaining} 秒", file=sys.stderr)
                time.sleep(2)
    
            # ---- 阶段 2: 开始轮询页面认证状态 ----
            print("开始检测登录状态...", file=sys.stderr)
            while time.time() - start < timeout:
                is_logged_in, _ = self.check_login_status(navigate=False)
                if is_logged_in:
                    print("检测到主站已登录!", file=sys.stderr)
                    time.sleep(5)
                    self.client._save_cookies()
                    return True
    
                elapsed = int(time.time() - start)
                remaining = timeout - elapsed
                if remaining > 0 and remaining % 15 == 0:
                    print(f"  仍在等待登录... 剩余 {remaining} 秒", file=sys.stderr)
                time.sleep(3)
    
            print("登录超时", file=sys.stderr)
            return False
    
    
    # ====== 顶层便捷函数 ======
    
    def check_login(
        cookie_path: str = DEFAULT_COOKIE_PATH,
    ) -> Tuple[bool, Optional[str]]:
        """检查登录状态"""
        client = XiaohongshuClient(headless=True, cookie_path=cookie_path)
        try:
            client.start()
            action = LoginAction(client)
            return action.check_login_status(navigate=True)
        finally:
            client.close()
    
    
    def check_creator_login(
        cookie_path: str = DEFAULT_COOKIE_PATH,
        headless: bool = True,
    ) -> bool:
        """Return whether the Creator Center is logged in."""
        client = XiaohongshuClient(headless=headless, cookie_path=cookie_path)
        try:
            client.start()
            return LoginAction(client).check_creator_login_status(navigate=True)
        finally:
            client.close()
    
    
    def creator_login(
        headless: bool = False,
        cookie_path: str = DEFAULT_COOKIE_PATH,
        timeout: int = 240,
    ) -> Dict[str, Any]:
        """Open the Creator Center and wait for phone-number login."""
        client = XiaohongshuClient(headless=headless, cookie_path=cookie_path)
        try:
            client.start()
            action = LoginAction(client)
            if action.check_creator_login_status(navigate=True):
                return {"status": "logged_in", "message": "创作者中心已登录"}
            if headless:
                return {"status": "login_required", "message": "创作者中心需要可见浏览器登录,请使用 --headless=false"}
            if action.wait_for_creator_login(timeout=timeout):
                return {"status": "logged_in", "message": "创作者中心登录成功"}
            return {"status": "timeout", "message": "创作者中心登录超时"}
        finally:
            client.close()
    
    
    def login(
        headless: bool = True,
        cookie_path: str = DEFAULT_COOKIE_PATH,
        timeout: int = 120,
    ) -> Dict[str, Any]:
        """
        登录小红书(生成二维码 + 等待扫码)
    
        Returns:
            登录结果字典
        """
        client = XiaohongshuClient(headless=headless, cookie_path=cookie_path)
        try:
            client.start()
            action = LoginAction(client)
    
            # 获取二维码
            qrcode_path, is_logged_in = action.get_wechat_qrcode()
            if is_logged_in:
                return {
                    "status": "logged_in",
                    "qrcode_path": None,
                    "username": "已登录用户",
                    "message": "已登录",
                }
    
            if qrcode_path:
                # 等待扫码
                success = action.wait_for_login(timeout=timeout)
                if success:
                    return {
                        "status": "logged_in",
                        "qrcode_path": None,
                        "username": "已登录用户",
                        "message": "扫码登录成功",
                    }
                return {
                    "status": "timeout",
                    "qrcode_path": qrcode_path,
                    "username": None,
                    "message": "扫码超时",
                }
    
            return {
                "status": "error",
                "qrcode_path": None,
                "username": None,
                "message": "获取二维码失败",
            }
        finally:
            client.close()
    
    
    def logout(cookie_path=None, user_data_dir=None):
        """删除浏览器持久化数据和 Cookie 文件,重置登录状态"""
        import shutil
        # 1. 删除持久化浏览器数据目录
        paths = profile_paths(env_profile())
        data_dir = user_data_dir or str(paths.user_data_dir)
        if os.path.exists(data_dir):
            shutil.rmtree(data_dir)
        # 2. 删除 cookie JSON
        path = cookie_path or DEFAULT_COOKIE_PATH
        if os.path.exists(path):
            os.remove(path)
        # 3. 删除策略文件
        strategy_file = os.path.join(os.path.expanduser("~"), ".xiaohongshu", "strategy.json")
        if os.path.exists(strategy_file):
            os.remove(strategy_file)
        return {"status": "ok", "message": "登录状态已清除"}
    
  • scripts/output_contracts.py9.3 KBf94b33d2f2d9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/profiles.py3.1 KB9cd890d19733upstream ↗
    """
    Browser profile path helpers.
    """
    
    from __future__ import annotations
    
    import os
    import re
    from dataclasses import dataclass
    from pathlib import Path
    
    DEFAULT_PROFILE = "default"
    DEFAULT_ROOT = Path(os.path.expanduser("~/.xiaohongshu"))
    PROFILE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$")
    
    
    class ProfileNameError(ValueError):
        """Invalid profile name."""
    
    
    @dataclass(frozen=True)
    class ProfilePaths:
        cookie_path: Path
        user_data_dir: Path
        session_path: Path
    
    
    def _normalize_profile(profile: str | None) -> str:
        name = (profile or DEFAULT_PROFILE).strip()
        if name == DEFAULT_PROFILE:
            return DEFAULT_PROFILE
        if not PROFILE_RE.match(name):
            raise ProfileNameError(
                "Profile names may contain letters, numbers, dot, underscore, or dash only."
            )
        return name
    
    
    def profile_paths(profile: str | None = None, root: str | Path | None = None) -> ProfilePaths:
        """Return cookie and browser-data paths for a profile."""
        root_path = Path(root) if root is not None else DEFAULT_ROOT
        name = _normalize_profile(profile)
    
        if name == DEFAULT_PROFILE:
            return ProfilePaths(
                cookie_path=root_path / "cookies.json",
                user_data_dir=root_path / "browser-data",
                session_path=root_path / "session.json",
            )
    
        profile_dir = root_path / "profiles" / name
        return ProfilePaths(
            cookie_path=profile_dir / "cookies.json",
            user_data_dir=profile_dir / "browser-data",
            session_path=profile_dir / "session.json",
        )
    
    
    def _profile_info(name: str, paths: ProfilePaths) -> dict[str, object]:
        return {
            "name": name,
            "cookie_path": str(paths.cookie_path),
            "user_data_dir": str(paths.user_data_dir),
            "cookie_exists": paths.cookie_path.exists(),
            "user_data_dir_exists": paths.user_data_dir.exists(),
        }
    
    
    def list_profiles(root: str | Path | None = None) -> list[dict[str, object]]:
        """List profiles that already have local state."""
        root_path = Path(root) if root is not None else DEFAULT_ROOT
        profiles: list[dict[str, object]] = []
    
        default_paths = profile_paths(DEFAULT_PROFILE, root=root_path)
        if (
            default_paths.cookie_path.exists()
            or default_paths.user_data_dir.exists()
            or default_paths.session_path.exists()
        ):
            profiles.append(_profile_info(DEFAULT_PROFILE, default_paths))
    
        profiles_dir = root_path / "profiles"
        if profiles_dir.exists():
            for profile_dir in sorted(path for path in profiles_dir.iterdir() if path.is_dir()):
                name = profile_dir.name
                if not PROFILE_RE.match(name):
                    continue
                paths = profile_paths(name, root=root_path)
                if (
                    paths.cookie_path.exists()
                    or paths.user_data_dir.exists()
                    or paths.session_path.exists()
                ):
                    profiles.append(_profile_info(name, paths))
    
        return profiles
    
    
    def env_profile() -> str | None:
        """Return the process profile override, if present."""
        return os.environ.get("XHS_PROFILE") or None
    
  • scripts/publish.py52 KB639f8beb78c8upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/quality.py2.4 KBb83a7ddc982bupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/release_check.py1.6 KBf61746c24dfdupstream ↗
    """Release version consistency checks."""
    
    from __future__ import annotations
    
    import argparse
    import sys
    from pathlib import Path
    
    try:
        import tomllib
    except ImportError:  # Python 3.10
        import tomli as tomllib
    
    from . import __version__
    
    
    def read_project_version(pyproject_path: Path = Path("pyproject.toml")) -> str:
        with pyproject_path.open("rb") as handle:
            project = tomllib.load(handle)["project"]
        return str(project["version"])
    
    
    def validate_release_version(tag: str, project_version: str, runtime_version: str) -> list[str]:
        errors = []
        expected_tag = f"v{project_version}"
        if tag != expected_tag:
            errors.append(f"release tag {tag!r} does not match project version {expected_tag!r}")
        if runtime_version != project_version:
            errors.append(
                f"runtime version {runtime_version!r} does not match project version {project_version!r}"
            )
        return errors
    
    
    def main(argv: list[str] | None = None) -> int:
        parser = argparse.ArgumentParser(description="Validate release version consistency.")
        parser.add_argument("tag", help="Git tag, for example v1.5.0")
        parser.add_argument("--pyproject", type=Path, default=Path("pyproject.toml"))
        args = parser.parse_args(argv)
    
        project_version = read_project_version(args.pyproject)
        errors = validate_release_version(args.tag, project_version, __version__)
        if errors:
            for error in errors:
                print(error, file=sys.stderr)
            return 1
        print(f"Release version verified: {args.tag}")
        return 0
    
    
    if __name__ == "__main__":
        raise SystemExit(main())
    
  • scripts/search.py14 KB6fe1c488474aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/selectors.py11 KB224e0a394156upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/session_store.py2.9 KB9df9a136b01eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/site_check.py8.3 KB15732a8a1249upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/skill_check.py1.1 KBb9ac7a48455dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/sop.py14 KB067301282e39upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/strategy.py10 KB267cde736cddupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/templates.py11 KBc0d51e86e916upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/test_gate.py669 Bb911d541f7b9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • scripts/user.py8.3 KB811c868cae56upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .coderabbit.yaml278 B870526a7c808upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .dockerignore212 Be87098ab9edbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .env.example356 B6933bc67e825upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/CODEOWNERS19 Bbbefc3d19239upstream ↗
    * @DeliciousBuding
    
  • .github/ISSUE_TEMPLATE/bug_report.md473 B4f573788b880upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/ISSUE_TEMPLATE/feature_request.md261 B1308b9e1193dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/PULL_REQUEST_TEMPLATE.md572 Ba5d32eb409c7upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/workflows/ci.yml3.3 KBc375d7e176d4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/workflows/pages.yml900 Be4090a952598upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .github/workflows/release.yml2.6 KB5fe5f1fd0f57upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • .gitignore422 B8ebf013edbd3upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • AGENTS.md2.0 KB4ba7929f9e4dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • CHANGELOG.md2.6 KBac544472d82fupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • CONTRIBUTING.md2.7 KBa5ec0b73bb25upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • data/.gitkeep0 Be69de29bb2d1upstream ↗
  • docker-compose.yml284 Bcd0da444e192upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • Dockerfile738 Ba04a3f4e01a6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/API.md4.3 KBf7587699b702upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/ARCHITECTURE.md3.9 KBbe9dc72be6bcupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/INSTALL.md3.9 KB47a5ef2d3bbdupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/INTEGRATIONS.md2.6 KB64606105fd4eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/PAGES.md2.2 KBcfed5a277428upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/REFERENCE.md1.8 KBe566be394d58upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/RELEASING.md1.7 KBd565de2f7148upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/ROADMAP.md1.3 KB7db18b27ad6eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • docs/SECURITY.md2.6 KB184499328a12upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • examples/demo/publish-ready.json429 Bf161946e5ebbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • examples/demo/search-result.json382 B9927dd0c1de5upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • LICENSE11 KB879e5aa31769upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • licenses/Apache-2.0.txt11 KB18a1e319f0aaupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • make.ps1279 B70ecd60fbb71upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • pyproject.toml1.7 KB7cc8c42bf0e6upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • README_EN.md5.8 KBb805c726d433upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/demo.html4.9 KB734f8d60b0e4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/index.html29 KB75eee69f9715upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/llms-full.txt4.0 KBb4f97234bf37upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/llms.txt2.9 KB7e0ac43a73bcupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/og-image.png57 KB4a454dd72f4aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/og-image.svg3.4 KB9322e6fe988dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/robots.txt239 Bc6b2dcef9bf7upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • site/sitemap.xml616 B58ed1e8953a1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/__init__.py0 Be69de29bb2d1upstream ↗
  • tests/conftest.py1.9 KB3521c1b41c1aupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/live/test_readonly_smoke.py807 B7230462a8f13upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_cli.py8.1 KBbe7abf69d7f2upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_client.py13 KB1c73ce0e61d9upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_comment.py6.2 KBffb203134b78upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_docs_check.py1.7 KBb2fe2b0fdd67upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_explore.py3.3 KB44fb9149cb13upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_interact.py6.9 KB366e9cd5dbfaupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_live_gate.py766 B7f138b9492baupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_login.py7.4 KB3a930a074404upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_output_contracts.py3.0 KB8cddb6f74146upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_profiles.py2.6 KB8527342c8b35upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_publish.py24 KBd065d5cb3bb4upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_publish_validation.py8.4 KB78da84eebdeeupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_quality.py1.2 KB61095f298332upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_release_check.py1014 B5571adb9d7dbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_search.py3.1 KB5f25af306beeupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_selectors.py5.5 KB9b33889181f1upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_session_store.py2.5 KB312c8b355df0upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_site_check.py3.5 KB794e81ad4356upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_skill_check.py846 Bf36960965470upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_sop.py7.3 KBd51c79c50a5eupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_strategy.py5.9 KB044080cde6dbupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_templates.py6.4 KB3b4d1738d383upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_test_harness.py267 Ba4f8cf55765dupstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • tests/test_user.py1.9 KB1b315f21e379upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • THIRD_PARTY_NOTICES.md795 Bbbdca5dd5827upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

  • uv.lock47 KB78d293892642upstream ↗

    Contents are not inlined in the catalog. Open the upstream file.

Plain-text copy, no login: /skill-bundles/deliciousbuding-xiaohongshu-skill.md

// REPO STATS

43 stars
1 open issues
Last commit: 2mo ago