Metadata-Version: 2.4
Name: xhs-cli
Version: 0.1.4
Summary: A CLI for Xiaohongshu (小红书) — search, read notes, view profiles
Project-URL: Homepage, https://github.com/jackwener/xhs-cli
Project-URL: Repository, https://github.com/jackwener/xhs-cli
Project-URL: Issues, https://github.com/jackwener/xhs-cli/issues
Author-email: jackwener <jakevingoo@gmail.com>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to the Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by the Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding any notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 jackwener
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: cli,redbook,xhs,xiaohongshu,小红书
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Utilities
Requires-Python: >=3.8
Requires-Dist: browser-cookie3>=0.19
Requires-Dist: camoufox[geoip]>=0.4
Requires-Dist: click>=8.0
Requires-Dist: playwright>=1.40
Requires-Dist: qrcode>=7.4
Requires-Dist: rich>=13.0
Description-Content-Type: text/markdown

# xhs-cli

[xiaohongshu-cli](https://github.com/jackwener/xiaohongshu-cli) 这是逆向 API 出来的版本。
速度更加快更加稳定。但是风控上应该不如当前这个直接用浏览器操作真实。

**中文** | [English](README_EN.md)

[![PyPI](https://img.shields.io/pypi/v/xhs-cli)](https://pypi.org/project/xhs-cli/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)

小红书命令行工具 — 在终端中搜索笔记、查看主页、点赞、收藏、评论。

## 推荐项目

- [twitter-cli](https://github.com/jackwener/twitter-cli) - 在终端中操作 X/Twitter 的 CLI 工具
- [bilibili-cli](https://github.com/jackwener/bilibili-cli) - 哔哩哔哩 CLI 工具

## 功能

- **搜索** — 按关键词搜索笔记，Rich 表格展示
- **阅读** — 查看笔记内容、数据、评论
- **用户资料** — 查看用户信息、笔记、粉丝、关注
- **推荐 Feed** — 获取探索页推荐内容
- **话题** — 搜索话题标签
- **互动** — 点赞/取消、收藏/取消、评论、删除笔记
- **发布** — 发布图文笔记
- **认证** — 自动提取 Chrome cookie，或 browser-assisted 扫码登录（终端二维码渲染）
- **JSON 输出** — 所有数据命令支持 `--json`
- **Token 自动缓存** — `xsec_token` 搜索后自动缓存，后续命令免手动传

## 命令一览

| 分类 | 命令 | 说明 |
|------|------|------|
| Auth | `login`, `logout`, `status`, `whoami` | 登录、退出、状态检查、查看个人资料 |
| Read | `search`, `read`, `feed`, `topics` | 搜索笔记、阅读详情、推荐 Feed、搜索话题 |
| Users | `user`, `user-posts`, `followers`, `following` | 查看资料、列出笔记/粉丝/关注 |
| Engage | `like`, `unlike`, `comment`, `delete` | 点赞、取消点赞、评论、删除笔记 |
| Favorites | `favorite`, `unfavorite`, `favorites` | 收藏、取消收藏、查看收藏列表 |
| Post | `post` | 发布图文笔记 |

> 所有数据命令支持 `--json` 输出。`xsec_token` 自动缓存，无需手动传递。

## 安装

需要 Python 3.8+。

```bash
# 推荐：使用 uv
uv tool install xhs-cli

# 或使用 pipx
pipx install xhs-cli
```

<details>
<summary>从源码安装（开发用）</summary>

```bash
git clone git@github.com:jackwener/xhs-cli.git
cd xhs-cli
uv sync
```

</details>

## 本地一键冒烟测试

在本地已登录（有 `~/.xhs-cli/cookies.json`）的情况下，直接运行：

```bash
./scripts/smoke_local.sh
```

可选地传递 pytest 参数（例如只跑某个用例）：

```bash
./scripts/smoke_local.sh -k whoami
```

默认只跑无副作用命令（`integration and not live_mutation`）。如需额外验证
`like/favorite/comment/post/delete`，显式开启：

```bash
XHS_SMOKE_MUTATION=1 ./scripts/smoke_local.sh
```

可选环境变量：

```bash
XHS_SMOKE_COMMENT_TEXT="smoke test comment"
XHS_SMOKE_POST_IMAGES="/abs/a.jpg,/abs/b.jpg"
XHS_SMOKE_POST_TITLE="smoke title"
XHS_SMOKE_POST_CONTENT="smoke content"
```

## 使用

### 登录

```bash
# 自动从 Chrome 提取 cookie（推荐）
xhs login

# 强制使用二维码登录（用于排查登录问题）
xhs login --qrcode

# 手动提供 cookie 字符串（至少包含 a1 和 web_session）
xhs login --cookie "a1=xxx; web_session=yyy"

# 快速检查已保存的登录状态（不启动浏览器，不读取浏览器 cookie）
xhs status

# 查看个人资料
xhs whoami
xhs whoami --json

# 退出登录
xhs logout
```

### 搜索

```bash
xhs search "咖啡"
xhs search "咖啡" --json
```

### 阅读笔记

```bash
# 查看笔记（xsec_token 从缓存自动解析）
xhs read <note_id>

# 包含评论
xhs read <note_id> --comments

# 手动指定 xsec_token
xhs read <note_id> --xsec-token <token>
```

### 用户

```bash
# 查看用户资料（使用内部 user_id，非小红书号）
xhs user <user_id>

# 列出用户笔记
xhs user-posts <user_id>

# 粉丝 / 关注
xhs followers <user_id>
xhs following <user_id>
```

### 推荐 & 话题

```bash
xhs feed
xhs topics "旅行"
```

### 互动

```bash
# 点赞 / 取消（xsec_token 自动解析）
xhs like <note_id>
xhs like <note_id> --undo

# 收藏 / 取消
xhs favorite <note_id>
xhs favorite <note_id> --undo

# 评论
xhs comment <note_id> "好棒！"

# 删除自己的笔记
xhs delete <note_id>

# 查看收藏列表
xhs favorites
xhs favorites --max 10
```

### 发布笔记

```bash
xhs post "标题" --image photo1.jpg --image photo2.jpg --content "正文内容"
xhs post "标题" --image photo1.jpg --content "正文内容" --json
```

### 其他

```bash
xhs --version
xhs -v search "咖啡"   # 调试日志
xhs --help
```

## 架构

```
CLI (click) → XhsClient (camoufox 浏览器)
                  ↓ 导航到真实页面
              window.__INITIAL_STATE__ → 提取结构化数据
```

使用 [camoufox](https://github.com/daijro/camoufox)（反指纹 Firefox）像真实用户一样浏览小红书。数据从页面的 `window.__INITIAL_STATE__` 中提取，与正常浏览完全一致。

## 工作原理

1. **认证** — 优先读取 `~/.xhs-cli/cookies.json`；未命中时通过 browser-cookie3 从本地 Chrome 提取 cookie。`xhs login --qrcode` 使用 browser-assisted 扫码登录，并在终端渲染二维码（`▀ ▄ █`）。
2. **登录态校验** — 登录后会校验会话是否为有效非 guest 会话，并做 feed/search 可用性探活；探活失败会提示重新登录。
3. **浏览** — 使用 camoufox 导航到真实页面，所有流量与正常用户浏览一致。
4. **数据提取** — 从 `window.__INITIAL_STATE__` 提取结构化数据。
5. **Token 缓存** — 搜索/Feed 后 `xsec_token` 自动缓存到 `~/.xhs-cli/token_cache.json`。
6. **互动操作** — 点赞、收藏、评论通过点击真实 DOM 按钮实现。

## 作为 AI Agent Skill 使用

xhs-cli 自带 [`SKILL.md`](./SKILL.md)，让 AI Agent 能自动学习并使用本工具。

### Claude Code / Antigravity

```bash
# 克隆到项目的 skills 目录
mkdir -p .agents/skills
git clone git@github.com:jackwener/xhs-cli.git .agents/skills/xhs-cli

# 或者只复制 SKILL.md
curl -o .agents/skills/xhs-cli/SKILL.md \
  https://raw.githubusercontent.com/jackwener/xhs-cli/main/SKILL.md
```

添加后，支持 `.agents/skills/` 的 AI Agent 会自动发现并使用 xhs-cli 命令。

### OpenClaw / ClawHub

官方支持 [OpenClaw](https://openclaw.ai) 和 [ClawHub](https://docs.openclaw.ai/tools/clawhub) 生态。通过 ClawHub 安装：

```bash
clawhub install xiaohongshu-cli
```

安装后即可在 OpenClaw 中直接使用所有 xhs-cli 命令。

## 注意事项

- Cookie 存储在 `~/.xhs-cli/cookies.json`，权限 `0600`。
- `xhs status` 只检查本地已保存 cookie，不会触发浏览器 cookie 提取。
- `xhs login --cookie` 要求 cookie 至少包含 `a1` 和 `web_session`。
- 登录后会自动做可用性探活；若会话仍为 guest/风控受限，会提示重新登录。
- `xhs post` 可能要求额外登录创作平台（`https://creator.xiaohongshu.com`）。
- 使用 headless Firefox，不会弹出浏览器窗口。
- 首次运行需下载 camoufox 浏览器（`python -m camoufox fetch`）。
- 用户资料查询需要内部 user_id（十六进制），不是小红书号。

## License

Apache License 2.0
