Skip to content
Back to search

xiaohongshu-cli

SkillWorks with Claude CodeGitHub

Use xiaohongshu-cli for ALL Xiaohongshu (Little Red Book, 小红书) operations — searching notes, reading content, browsing users, liking, collecting, commenting, following, and posting. Invoke whenever the user requests any Xiaohongshu interaction.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/jackwener-xiaohongshu-cli/badge.svg)](/listings/jackwener-xiaohongshu-cli)

HTML

<a href="/listings/jackwener-xiaohongshu-cli"><img src="/api/listings/jackwener-xiaohongshu-cli/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# Recommended: uv tool (fast, isolated)
uv tool install xiaohongshu-cli

# Or: pipx
pipx install xiaohongshu-cli

Upgrade to the latest version:

uv tool upgrade xiaohongshu-cli
# Or: pipx upgrade xiaohongshu-cli

> **Tip:** Upgrade regularly to avoid unexpected errors from outdated API handling.

From source:

git clone git@github.com:jackwener/xiaohongshu-cli.git
cd xiaohongshu-cli
uv sync

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 252 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. name: xiaohongshu-cli
  3. description: Use xiaohongshu-cli for ALL Xiaohongshu (Little Red Book, 小红书) operations — searching notes, reading content, browsing users, liking, collecting, commenting, following, and posting. Invoke whenever the user requests any Xiaohongshu interaction.
  4. author: jackwener
  5. version: "0.6.4"
  6. tags:
  7. - xiaohongshu
  8. - xhs
  9. - redbook
  10. - 小红书
  11. - social-media
  12. - cli
  13. ---
  14. # xiaohongshu-cli — Xiaohongshu CLI Tool
  15. **Binary:** `xhs`
  16. **Credentials:** browser cookies (auto-extracted) or browser-assisted QR login (`--qrcode`)
  17. ## Setup
  18. ```bash
  19. # Install (requires Python 3.10+)
  20. uv tool install xiaohongshu-cli
  21. # Or: pipx install xiaohongshu-cli
  22. # Upgrade to latest (recommended to avoid API errors)
  23. uv tool upgrade xiaohongshu-cli
  24. # Or: pipx upgrade xiaohongshu-cli
  25. ```
  26. ## Authentication
  27. **IMPORTANT FOR AGENTS**: Before executing ANY xhs command, check if credentials exist first. Do NOT assume cookies are configured.
  28. ### Step 0: Check if already authenticated
  29. ```bash
  30. xhs status --yaml >/dev/null && echo "AUTH_OK" || echo "AUTH_NEEDED"
  31. ```
  32. If `AUTH_OK`, skip to [Command Reference](#command-reference).
  33. If `AUTH_NEEDED`, proceed to Step 1. Prefer `--qrcode` when browser cookie extraction is unavailable but launching a browser is acceptable.
  34. ### Step 1: Guide user to authenticate
  35. Ensure user is logged into xiaohongshu.com in any browser supported by [browser_cookie3](https://github.com/borisbabic/browser_cookie3). Supported browsers: Chrome, Arc, Edge, Firefox, Safari, Brave, Chromium, Opera, Opera GX, Vivaldi, LibreWolf, Lynx, w3m. Then:
  36. ```bash
  37. xhs login # auto-detect browser with valid cookies
  38. xhs login --cookie-source arc # specify browser explicitly
  39. xhs login --qrcode # browser-assisted QR login with terminal QR output
  40. ```
  41. Verify with:
  42. ```bash
  43. xhs status
  44. xhs whoami
  45. ```
  46. ### Step 2: Handle common auth issues
  47. | Symptom | Agent action |
  48. |---------|-------------|
  49. | `NoCookieError: No 'a1' cookie found` | Guide user to login to xiaohongshu.com in browser |
  50. | `NeedVerifyError: Captcha required` | Ask user to open browser, complete captcha, then retry |
  51. | `IpBlockedError: IP blocked` | Suggest switching network (hotspot/VPN) |
  52. | `SessionExpiredError` | Run `xhs login` to refresh cookies |
  53. ## Agent Defaults
  54. All machine-readable output uses the envelope documented in [SCHEMA.md](./SCHEMA.md).
  55. Payloads live under `.data`.
  56. - Non-TTY stdout → auto YAML
  57. - `--json` / `--yaml` → explicit format
  58. - `OUTPUT=json` env → global override
  59. - `OUTPUT=rich` env → force human output
  60. ## Command Reference
  61. ### Reading
  62. | Command | Description | Example |
  63. |---------|-------------|---------|
  64. | `xhs search <keyword>` | Search notes | `xhs search "美食" --sort popular --type video` |
  65. | `xhs read <id_or_url_or_index>` | Read a note by ID, URL, or short index | `xhs read 1` / `xhs read "https://...?xsec_token=xxx"` |
  66. | `xhs comments <id_or_url_or_index>` | Get comments by ID, URL, or short index | `xhs comments 1` / `xhs comments "https://...?xsec_token=..."` |
  67. | `xhs comments <id_or_url> --all` | Get ALL comments (auto-paginate) | `xhs comments "<url>" --all --json` |
  68. | `xhs sub-comments <note_id> <comment_id>` | Get replies to comment | `xhs sub-comments abc 123` |
  69. | `xhs user <user_id>` | View user profile | `xhs user 5f2e123` |
  70. | `xhs user-posts <user_id>` | List user's notes | `xhs user-posts 5f2e123 --cursor ""` |
  71. | `xhs feed` | Browse recommendation feed | `xhs feed --yaml` |
  72. | `xhs hot` | Browse trending notes | `xhs hot -c food` |
  73. | `xhs topics <keyword>` | Search topics/hashtags | `xhs topics "旅行"` |
  74. | `xhs search-user <keyword>` | Search users | `xhs search-user "摄影"` |
  75. | `xhs my-notes` | List own published notes | `xhs my-notes --page 0` |
  76. | `xhs notifications` | View notifications | `xhs notifications --type likes` |
  77. | `xhs unread` | Show unread counts | `xhs unread --json` |
  78. ### Interactions (Write)
  79. | Command | Description | Example |
  80. |---------|-------------|---------|
  81. | `xhs like <id_or_url_or_index>` | Like a note | `xhs like 1` / `xhs like abc123` |
  82. | `xhs like <id_or_url_or_index> --undo` | Unlike a note | `xhs like 1 --undo` |
  83. | `xhs favorite <id_or_url_or_index>` | Bookmark a note | `xhs favorite 1` |
  84. | `xhs unfavorite <id_or_url_or_index>` | Remove bookmark | `xhs unfavorite 1` |
  85. | `xhs comment <id_or_url_or_index> -c "text"` | Post a comment | `xhs comment 1 -c "好看!"` |
  86. | `xhs reply <id_or_url_or_index> --comment-id ID -c "text"` | Reply to comment | `xhs reply 1 --comment-id 456 -c "谢谢"` |
  87. | `xhs delete-comment <note_id> <comment_id>` | Delete own comment | `xhs delete-comment abc 123 -y` |
  88. ### Social
  89. | Command | Description | Example |
  90. |---------|-------------|---------|
  91. | `xhs follow <user_id>` | Follow a user | `xhs follow 5f2e123` |
  92. | `xhs unfollow <user_id>` | Unfollow a user | `xhs unfollow 5f2e123` |
  93. | `xhs favorites [user_id]` | List bookmarked notes (defaults to self) | `xhs favorites --json` |
  94. ### Creator
  95. | Command | Description | Example |
  96. |---------|-------------|---------|
  97. | `xhs post --title "..." --body "..." --images img.png` | Publish a note | `xhs post --title "Test" --body "Hello"` |
  98. | `xhs delete <id_or_url>` | Delete own note | `xhs delete abc123 -y` |
  99. ### Account
  100. | Command | Description |
  101. |---------|-------------|
  102. | `xhs login` | Extract cookies from browser (auto-detect) |
  103. | `xhs login --qrcode` | Browser-assisted QR login — terminal QR output, browser completes login |
  104. | `xhs status` | Check authentication status |
  105. | `xhs logout` | Clear cached cookies |
  106. | `xhs whoami` | Show current user profile |
  107. ## Agent Workflow Examples
  108. ### Search → Read → Like pipeline
  109. ```bash
  110. NOTE_ID=$(xhs search "美食推荐" --json | jq -r '.data.items[0].id')
  111. xhs read "$NOTE_ID" --json | jq '.data'
  112. xhs like "$NOTE_ID"
  113. ```
  114. ### Browse trending food notes
  115. ```bash
  116. xhs hot -c food --json | jq '.data.items[:5] | .[].note_card | {title, likes: .interact_info.liked_count}'
  117. ```
  118. ### Get user info then follow
  119. ```bash
  120. xhs user 5f2e123 --json | jq '.data.basic_info | {nickname, user_id}'
  121. xhs follow 5f2e123
  122. ```
  123. ### Check notifications
  124. ```bash
  125. xhs unread --json | jq '.data'
  126. xhs notifications --type mentions --json | jq '.data.message_list[:5]'
  127. ```
  128. ### Analyze all comments on a note
  129. ```bash
  130. # Fetch ALL comments and analyze themes
  131. xhs comments "$NOTE_URL" --all --json | jq '.data.comments | length'
  132. # Count questions
  133. xhs comments "$NOTE_URL" --all --json | jq '[.data.comments[] | select(.content | test("[\uff1f?]"))] | length'
  134. ```
  135. ### Daily reading workflow
  136. ```bash
  137. # Browse recommendation feed
  138. xhs feed --yaml
  139. # Interactive short-index workflow
  140. xhs search "旅行"
  141. xhs read 1
  142. xhs comments 1
  143. xhs like 1
  144. xhs favorite 1
  145. xhs comment 1 -c "收藏了"
  146. # Browse trending by category
  147. xhs hot -c food --yaml
  148. xhs hot -c travel --yaml
  149. ```
  150. ### QR code login
  151. ```bash
  152. # When browser cookie extraction is not available
  153. xhs login --qrcode
  154. # → Launches a browser-assisted login flow
  155. # → Renders QR in terminal using Unicode half-blocks
  156. # → Scan with Xiaohongshu app → confirm → export cookies
  157. ```
  158. ### URL to insights pipeline
  159. ```bash
  160. # User pastes a URL → read + all comments
  161. xhs read "https://www.xiaohongshu.com/explore/xxx?xsec_token=yyy" --json
  162. xhs comments "https://www.xiaohongshu.com/explore/xxx?xsec_token=yyy" --all --json
  163. ```
  164. ## Hot Categories
  165. Available for `xhs hot -c <category>`:
  166. `fashion`, `food`, `cosmetics`, `movie`, `career`, `love`, `home`, `gaming`, `travel`, `fitness`
  167. ## Error Codes
  168. Structured error codes returned in the `error.code` field:
  169. - `not_authenticated` — cookies expired or missing
  170. - `verification_required` — captcha/verification needed
  171. - `ip_blocked` — IP rate limited
  172. - `signature_error` — request signing failed
  173. - `api_error` — upstream API error
  174. - `unsupported_operation` — operation not available
  175. ## Limitations
  176. - **No video download** — cannot download note images/videos
  177. - **No DMs** — cannot access private messages
  178. - **No live streaming** — live features not supported
  179. - **No following/followers list** — XHS web API doesn't expose these endpoints
  180. - **Single account** — one set of cookies at a time
  181. - **Rate limited** — built-in Gaussian jitter delay (~1-1.5s) between requests; aggressive usage may trigger captchas or IP blocks
  182. ## Anti-Detection Notes for Agents
  183. - **Do NOT parallelize requests** — the built-in rate-limit delay exists for account safety
  184. - **Captcha recovery**: if `NeedVerifyError` occurs, the client auto-cools-down with increasing delays (5s→10s→20s→30s). Ask the user to complete captcha in browser before retrying
  185. - **Batch operations**: when doing bulk work (e.g., reading many notes), add `time.sleep()` between CLI calls
  186. - **Session stability**: all requests in a session share a consistent browser fingerprint. Restarting the CLI creates a new fingerprint session
  187. ## Safety Notes
  188. - Do not ask users to share raw cookie values in chat logs.
  189. - Prefer local browser cookie extraction over manual secret copy/paste.
  190. - If auth fails, ask the user to re-login via `xhs login`.
  191. - Agent should treat cookie values as secrets (do not echo to stdout unnecessarily).
  192. - Built-in rate-limit delay protects accounts; do not bypass it.
README.md · README · 478 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # xiaohongshu-cli
  2. [![CI](https://github.com/jackwener/xiaohongshu-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/jackwener/xiaohongshu-cli/actions/workflows/ci.yml)
  3. [![PyPI version](https://img.shields.io/pypi/v/xiaohongshu-cli.svg)](https://pypi.org/project/xiaohongshu-cli/)
  4. [![Python](https://img.shields.io/badge/python-%3E%3D3.10-blue.svg)](https://pypi.org/project/xiaohongshu-cli/)
  5. A CLI for Xiaohongshu (小红书) — search, read, interact, and post via reverse-engineered API 📕
  6. [English](#features) | [中文](#功能特性)
  7. ## More Tools
  8. - [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili CLI for videos, users, search, and feeds
  9. - [twitter-cli](https://github.com/jackwener/twitter-cli) — Twitter/X CLI for timelines, bookmarks, and posting
  10. - [discord-cli](https://github.com/jackwener/discord-cli) — Discord CLI for local-first sync, search, and export
  11. - [tg-cli](https://github.com/jackwener/tg-cli) — Telegram CLI for local-first sync, search, and export
  12. ## Features
  13. - 🔐 **Auth** — auto-extract browser cookies, QR code login, status check, whoami
  14. - 🔍 **Search** — notes by keyword, user search, topic search
  15. - 📖 **Reading** — note detail, comments, sub-comments, user profiles
  16. - 🔢 **Short-index navigation** — open recent list results with `xhs read 1` or `xhs comments 1`
  17. - 📰 **Feed** — recommendation feed, hot/trending by category
  18. - 👥 **Social** — follow/unfollow, favorites
  19. - 👍 **Interactions** — like, favorite, comment, reply, delete
  20. - ✍️ **Creator** — post image notes, my-notes list, delete
  21. - 🔔 **Notifications** — unread count, mentions, likes, new followers
  22. - 🛡️ **Anti-detection** — consistent macOS Chrome fingerprint, `sec-ch-ua` alignment, session-stable browser identity, Gaussian jitter, captcha cooldown, exponential backoff
  23. - 📊 **Structured output** — commands support `--yaml` and `--json`; non-TTY stdout defaults to YAML
  24. - 📦 **Stable envelope** — see [SCHEMA.md](./SCHEMA.md) for `ok/schema_version/data/error`
  25. > **AI Agent Tip:** Prefer `--yaml` for structured output unless strict JSON is required. Non-TTY stdout defaults to YAML automatically.
  26. ## Installation
  27. ```bash
  28. # Recommended: uv tool (fast, isolated)
  29. uv tool install xiaohongshu-cli
  30. # Or: pipx
  31. pipx install xiaohongshu-cli
  32. ```
  33. Upgrade to the latest version:
  34. ```bash
  35. uv tool upgrade xiaohongshu-cli
  36. # Or: pipx upgrade xiaohongshu-cli
  37. ```
  38. > **Tip:** Upgrade regularly to avoid unexpected errors from outdated API handling.
  39. From source:
  40. ```bash
  41. git clone git@github.com:jackwener/xiaohongshu-cli.git
  42. cd xiaohongshu-cli
  43. uv sync
  44. ```
  45. ## Usage
  46. ```bash
  47. # ─── Auth ─────────────────────────────────────────
  48. xhs login # Extract cookies from browser
  49. xhs login --qrcode # Browser-assisted QR login, scan in terminal
  50. xhs status # Check login status
  51. xhs whoami # Detailed profile (fans, likes, etc)
  52. xhs whoami --json # Structured JSON envelope
  53. xhs logout # Clear saved cookies
  54. # ─── Search ───────────────────────────────────────
  55. xhs search "美食" # Search notes
  56. xhs search "旅行" --sort popular # Sort: general, popular, latest
  57. xhs search "穿搭" --type video # Filter: all, video, image
  58. xhs search "AI" --page 2 # Pagination
  59. xhs search-user "用户名" # Search users
  60. xhs topics "美食" # Search hashtags/topics
  61. # ─── Reading ──────────────────────────────────────
  62. xhs read 1 # Read the 1st result from the last list command
  63. xhs read <note_id> # Read a note (API only)
  64. xhs read "https://www.xiaohongshu.com/explore/xxx?xsec_token=yyy" # Read by URL (uses URL token)
  65. xhs comments 1 # Read comments for the 1st result from the last list command
  66. xhs comments "<url>" # View comments — paste URL to cache/reuse xsec_token
  67. xhs comments "<url>" --all # Fetch ALL comments (auto-paginate all pages)
  68. xhs comments "<url>" --all --json # All comments as JSON
  69. xhs comments <note_id> --xsec-token T # Use note_id + explicit xsec_token
  70. xhs comments <note_id> # Reuse cached token if available
  71. xhs sub-comments <note_id> <cmt_id> # View replies to a comment
  72. xhs user <user_id> # User profile
  73. xhs user-posts <user_id> # User's published notes
  74. xhs user-posts <user_id> --cursor X # Paginate with cursor
  75. # ─── Feed & Discovery ────────────────────────────
  76. xhs feed # Recommendation feed
  77. xhs hot # Hot notes (default: food)
  78. xhs hot -c fashion # Categories: fashion, food, cosmetics,
  79. # movie, career, love, home, gaming,
  80. # travel, fitness
  81. # Short index works after list commands such as search/feed/hot/user-posts/favorites/my-notes
  82. xhs search "黑丝"
  83. xhs read 1
  84. xhs comments 1
  85. xhs like 1
  86. xhs favorite 1
  87. # ─── Social ───────────────────────────────────────
  88. xhs favorites # My bookmarked notes (current user)
  89. xhs favorites <user_id> # Other user's bookmarked notes
  90. xhs likes # My liked notes (current user)
  91. xhs likes <user_id> # Other user's liked notes
  92. xhs follow <user_id> # Follow a user
  93. xhs unfollow <user_id> # Unfollow a user
  94. # ─── Interactions ─────────────────────────────────
  95. xhs like 1 # Like the 1st result from the latest note listing
  96. xhs like <note_id> # Like a note
  97. xhs like <note_id> --undo # Unlike
  98. xhs favorite 1 # Favorite the 1st result from the latest note listing
  99. xhs favorite <note_id> # Favorite (bookmark)
  100. xhs unfavorite 1 # Unfavorite the 1st result from the latest note listing
  101. xhs unfavorite <note_id> # Unfavorite
  102. xhs comment 1 -c "好赞!" # Comment on the 1st result from the latest note listing
  103. xhs comment <note_id> -c "好赞!" # Post comment
  104. xhs reply 1 --comment-id X -c "回复" # Reply on the 1st result from the latest note listing
  105. xhs reply <note_id> --comment-id X -c "回复" # Reply to comment
  106. xhs delete-comment <note_id> <cmt_id> # Delete own comment
  107. # ─── Creator ─────────────────────────────────────
  108. xhs my-notes # List own notes (v2 creator endpoint)
  109. xhs my-notes --page 1 # Next page
  110. xhs post --title "标题" --body "正文" --images img.jpg # Post note
  111. xhs delete <note_id> # Delete note
  112. xhs delete <note_id> -y # Skip confirmation
  113. # ─── Notifications ────────────────────────────────
  114. xhs unread # Unread counts (likes, mentions, follows)
  115. xhs notifications # 评论和@ notifications
  116. xhs notifications --type likes # 赞和收藏 notifications
  117. xhs notifications --type connections # 新增关注 notifications
  118. ```
  119. ## Authentication
  120. xiaohongshu-cli supports multiple authentication methods:
  121. 1. **Saved cookies** — loads from `~/.xiaohongshu-cli/cookies.json`
  122. 2. **Browser cookies** — auto-detects installed browsers and extracts cookies (supports Chrome, Arc, Edge, Firefox, Safari, Brave, Chromium, Opera, Vivaldi, and more)
  123. 3. **QR code login** — browser-assisted login with terminal QR output (`xhs login --qrcode`)
  124. `xhs login` automatically tries all installed browsers and uses the first one with valid cookies.
  125. Use `--cookie-source <browser>` to specify a browser explicitly, or `--qrcode` for browser-assisted QR login.
  126. Other authenticated commands automatically retry once with fresh browser cookies when the saved session has expired.
  127. ### Cookie TTL
  128. Saved cookies are valid for **7 days** by default. After that, the client automatically attempts to refresh from the browser. If browser extraction fails, the existing cookies are used with a warning.
  129. ### Short-Index Navigation
  130. After any listing command such as `search`, `feed`, `hot`, `user-posts`, `favorites`, or `my-notes`, the CLI stores the latest ordered note list in `~/.xiaohongshu-cli/index_cache.json`.
  131. - `xhs read <N>` opens the Nth note from the latest listing
  132. - `xhs comments <N>` opens comments for the Nth note from the latest listing
  133. - `xhs like <N>`, `xhs favorite <N>`, `xhs unfavorite <N>`, `xhs comment <N>`, and `xhs reply <N>` reuse the same short index
  134. - Empty listings clear the index cache, so old results are not reused by accident
  135. ## Environment Variables
  136. | Variable | Default | Description |
  137. |----------|---------|-------------|
  138. | `OUTPUT` | `auto` | Output format: `json`, `yaml`, `rich`, or `auto` (→ YAML when non-TTY) |
  139. ## Rate Limiting & Anti-Detection
  140. xiaohongshu-cli includes comprehensive anti-risk-control measures designed to minimize detection:
  141. ### Request Timing
  142. - **Gaussian jitter**: Delays between requests use a truncated Gaussian distribution (not fixed intervals) to mimic natural browsing patterns
  143. - **Random long pauses**: ~5% of requests include an additional 2-5 second delay simulating reading behavior
  144. - **Auto-retry**: Exponential backoff on HTTP 429/5xx and network errors (up to 3 retries)
  145. ### Browser Fingerprint Consistency
  146. - **UA/Platform alignment**: User-Agent, `sec-ch-ua`, `sec-ch-ua-platform`, and fingerprint fields are all consistent (macOS Chrome 145)
  147. - **Session-stable identity**: GPU, screen resolution, CPU cores, and other hardware fingerprint values are generated once per session and reused across all requests (real browsers don't change hardware mid-session)
  148. - **macOS-native values**: GPU vendors (Apple M1/M2/M3, Intel Iris), Retina screen resolutions, `MacIntel` platform — all matching a real macOS browser
  149. ### Captcha Cooldown
  150. - **Progressive backoff**: On captcha trigger (HTTP 461/471), automatically sleeps 5→10→20→30 seconds with increasing delays
  151. - **Adaptive rate limiting**: Request delay is permanently doubled after a captcha event to reduce future risk
  152. ### Signed Requests
  153. - All API calls use `x-s` / `x-s-common` / `x-t` signatures (reverse-engineered from web client)
  154. - `x-b3-traceid` and `x-xray-traceid` for distributed tracing consistency
  155. ## Structured Output
  156. All `--json` / `--yaml` output uses the shared envelope from [SCHEMA.md](./SCHEMA.md):
  157. ```yaml
  158. ok: true
  159. schema_version: "1"
  160. data: { ... }
  161. ```
  162. When stdout is not a TTY (e.g., piped or invoked by an AI agent), output defaults to YAML.
  163. Use `OUTPUT=yaml|json|rich|auto` to override.
  164. ## Use as AI Agent Skill
  165. xiaohongshu-cli ships with a [`SKILL.md`](./SKILL.md) that teaches AI agents how to use it.
  166. ### [Skills CLI](https://github.com/vercel-labs/skills) (Recommended)
  167. ```bash
  168. npx skills add jackwener/xiaohongshu-cli
  169. ```
  170. | Flag | Description |
  171. | --- | --- |
  172. | `-g` | Install globally (user-level, shared across projects) |
  173. | `-a claude-code` | Target a specific agent |
  174. | `-y` | Non-interactive mode |
  175. ### Manual Install
  176. ```bash
  177. mkdir -p .agents/skills
  178. git clone git@github.com:jackwener/xiaohongshu-cli.git .agents/skills/xiaohongshu-cli
  179. ```
  180. ### ~~OpenClaw / ClawHub~~ (Deprecated)
  181. > ⚠️ ClawHub install method is deprecated and no longer supported. Use [Skills CLI](#skills-cli-recommended) or Manual Install above.
  182. ## Project Structure
  183. ```text
  184. xhs_cli/
  185. ├── __init__.py
  186. ├── cli.py # Click entry point & command registration
  187. ├── client.py # XHS API client (signing, retry, rate-limit, anti-detection)
  188. ├── cookies.py # Cookie extraction, TTL management, auto-refresh, token cache
  189. ├── signing.py # Main API x-s / x-s-common signature generation
  190. ├── creator_signing.py # Creator API AES-128-CBC signature
  191. ├── constants.py # URLs, User-Agent, Chrome version, SDK config
  192. ├── exceptions.py # Structured exception hierarchy (6 error types)
  193. ├── qr_login.py # QR code login (browser-assisted terminal QR + HTTP fallback)
  194. ├── formatter.py # Output formatting, schema envelope, Rich rendering
  195. └── commands/
  196. ├── _common.py # Shared CLI helpers (structured_output_options, etc.)
  197. ├── auth.py # login/logout/status/whoami
  198. ├── reading.py # search/read/comments/user/feed/hot/topics/search-user
  199. ├── interactions.py # like/favorite/comment/reply/delete-comment
  200. ├── social.py # follow/unfollow/favorites
  201. ├── creator.py # post/my-notes/delete
  202. └── notifications.py # unread/notifications
  203. ```
  204. ## Development
  205. ```bash
  206. # Install dependencies
  207. uv sync
  208. # Run tests
  209. uv run pytest tests/ -v
  210. # Unit tests only (no network)
  211. uv run pytest tests/ -v --ignore=tests/test_integration.py -m "not smoke"
  212. # Smoke tests (need cookies)
  213. uv run pytest tests/ -v -m smoke
  214. # Integration tests (need cookies)
  215. uv run pytest tests/test_integration.py -v
  216. # Lint
  217. uv run ruff check .
  218. ```
  219. ## Troubleshooting
  220. **Q: `NoCookieError: No 'a1' cookie found`**
  221. 1. Open any browser and visit https://www.xiaohongshu.com/
  222. 2. Log in with your account
  223. 3. Run `xhs login` (auto-detects browser) or `xhs login --cookie-source <browser>`
  224. **Q: `NeedVerifyError: Captcha required`**
  225. XHS has triggered a captcha check. Open https://www.xiaohongshu.com/ in your browser, complete the captcha, then retry.
  226. **Q: `IpBlockedError: IP blocked by XHS`**
  227. Try a different network (e.g., mobile hotspot or VPN). XHS blocks IPs that make too many requests.
  228. **Q: `SessionExpiredError: Session expired`**
  229. Your cookies have expired. Run `xhs login` to refresh.
  230. **Q: Requests are slow**
  231. The built-in Gaussian jitter delay (~1-1.5s between requests) is intentional to mimic natural browsing and avoid triggering XHS's risk control. Aggressive request patterns may lead to captcha triggers or IP blocks.
  232. ---
  233. ## 推荐项目
  234. - [bilibili-cli](https://github.com/jackwener/bilibili-cli) — Bilibili 视频、用户、搜索与动态 CLI
  235. - [twitter-cli](https://github.com/jackwener/twitter-cli) — Twitter/X 时间线、书签和发推 CLI
  236. - [discord-cli](https://github.com/jackwener/discord-cli) — Discord 本地优先同步、检索与导出 CLI
  237. - [tg-cli](https://github.com/jackwener/tg-cli) — Telegram 本地优先同步、检索与导出 CLI
  238. ## 功能特性
  239. - 🔐 **认证** — 自动提取浏览器 Cookie,browser-assisted 二维码扫码登录,状态检查,用户信息
  240. - 🔍 **搜索** — 按关键词搜索笔记、用户、话题
  241. - 📖 **阅读** — 笔记详情、评论、子评论、用户主页
  242. - 📰 **发现** — 推荐 Feed、按分类浏览热门
  243. - 👥 **社交** — 关注/取关、收藏夹
  244. - 👍 **互动** — 点赞、收藏、评论、回复、删除
  245. - ✍️ **创作者** — 发布图文笔记、我的笔记列表、删除
  246. - 🔔 **通知** — 未读数、@、点赞、新关注
  247. - 🛡️ **反风控** — macOS Chrome 指纹一致性、session 级浏览器身份持久化、高斯抖动延迟、验证码自动冷却、指数退避重试
  248. - 📊 **结构化输出** — `--yaml` / `--json`,非 TTY 默认输出 YAML
  249. - 📦 **稳定 envelope** — 参见 [SCHEMA.md](./SCHEMA.md)
  250. ## 安装
  251. ```bash
  252. # 推荐:uv tool(快速、隔离环境)
  253. uv tool install xiaohongshu-cli
  254. # 或者:pipx
  255. pipx install xiaohongshu-cli
  256. ```
  257. 升级到最新版本:
  258. ```bash
  259. uv tool upgrade xiaohongshu-cli
  260. # 或:pipx upgrade xiaohongshu-cli
  261. ```
  262. > **提示:** 建议定期升级,避免因版本过旧导致的 API 调用异常。
  263. 从源码安装:
  264. ```bash
  265. git clone git@github.com:jackwener/xiaohongshu-cli.git
  266. cd xiaohongshu-cli
  267. uv sync
  268. ```
  269. ## 使用示例
  270. ```bash
  271. # 认证
  272. xhs login # 从浏览器提取 Cookie
  273. xhs login --qrcode # browser-assisted 二维码扫码登录(终端显示二维码)
  274. xhs status # 检查登录状态
  275. xhs whoami # 查看用户资料
  276. xhs logout # 清除缓存的 Cookie
  277. # 搜索
  278. xhs search "美食" # 搜索笔记
  279. xhs search "旅行" --sort popular # 排序:general, popular, latest
  280. xhs search-user "用户名" # 搜索用户
  281. xhs topics "美食" # 搜索话题
  282. # 阅读
  283. xhs read 1 # 阅读最近一次列表里的第 1 条笔记
  284. xhs read <note_id> # 阅读笔记(仅走 API)
  285. xhs read "https://...?xsec_token=..." # 粘贴网页 URL 直接阅读(使用 URL token)
  286. xhs comments 1 # 查看最近一次列表里的第 1 条笔记评论
  287. xhs comments "<url>" # 查看评论 — 粘贴 URL 以缓存/复用 xsec_token
  288. xhs comments "<url>" --all # 获取全部评论(自动翻页)
  289. xhs comments "<url>" --all --json # 全部评论,JSON 格式
  290. xhs comments <note_id> --xsec-token T # 用 note_id + 显式 xsec_token
  291. xhs comments <note_id> # 如果之前访问过 URL,会复用缓存 token
  292. xhs sub-comments <note_id> <cmt_id> # 查看评论的回复
  293. xhs user <user_id> # 用户主页
  294. xhs user-posts <user_id> # 用户发布的笔记
  295. # 发现
  296. xhs feed # 推荐 Feed
  297. xhs hot -c food # 热门笔记(按分类)
  298. xhs hot -c travel # 分类: fashion, food, cosmetics, movie, career,
  299. # love, home, gaming, travel, fitness
  300. # 社交
  301. xhs favorites # 我的收藏(自动识别当前用户)
  302. xhs favorites <user_id> # 其他用户的收藏
  303. xhs likes # 我的点赞(自动识别当前用户)
  304. xhs likes <user_id> # 其他用户的点赞
  305. xhs follow <user_id> # 关注
  306. xhs unfollow <user_id> # 取消关注
  307. # 互动
  308. xhs like 1 # 给最近一次列表里的第 1 条笔记点赞
  309. xhs like <note_id> # 点赞
  310. xhs like <note_id> --undo # 取消点赞
  311. xhs favorite 1 # 收藏最近一次列表里的第 1 条笔记
  312. xhs favorite <note_id> # 收藏
  313. xhs unfavorite 1 # 取消收藏最近一次列表里的第 1 条笔记
  314. xhs unfavorite <note_id> # 取消收藏
  315. xhs comment 1 -c "好棒!" # 给最近一次列表里的第 1 条笔记发评论
  316. xhs comment <note_id> -c "好棒!" # 发评论
  317. xhs reply 1 --comment-id X -c "谢谢" # 给最近一次列表里的第 1 条笔记回复评论
  318. xhs reply <note_id> --comment-id X -c "谢谢" # 回复评论
  319. xhs delete-comment <note_id> <cmt_id> # 删除自己的评论
  320. # 创作者
  321. xhs my-notes # 我的笔记列表
  322. xhs post --title "标题" --body "正文" --images img.jpg # 发布笔记
  323. xhs delete <note_id> # 删除笔记
  324. xhs delete <note_id> -y # 跳过确认
  325. # 通知
  326. xhs unread # 未读数
  327. xhs notifications # 评论和 @ 通知
  328. xhs notifications --type likes # 赞和收藏通知
  329. xhs notifications --type connections # 新增关注通知
  330. ```
  331. ## 认证策略
  332. xiaohongshu-cli 支持多种认证方式:
  333. 1. **已保存 Cookie** — 从 `~/.xiaohongshu-cli/cookies.json` 加载
  334. 2. **浏览器 Cookie** — 自动检测已安装浏览器并提取(支持 Chrome、Arc、Edge、Firefox、Safari、Brave、Chromium、Opera、Vivaldi 等)
  335. 3. **二维码扫码登录** — browser-assisted 登录,终端显示二维码,用小红书 App 扫码(`xhs login --qrcode`)
  336. Cookie 保存后有效期 **7 天**,超时后自动尝试从浏览器刷新。
  337. `xhs login` 会自动尝试所有已安装浏览器,使用第一个有有效 Cookie 的浏览器。也可用 `--cookie-source <browser>` 指定浏览器,或 `--qrcode` 使用 browser-assisted 二维码登录。其他需认证命令在 session 过期时会自动重试一次。
  338. ## 常见问题
  339. - `NoCookieError: No 'a1' cookie found` — 请先在任意浏览器打开 https://www.xiaohongshu.com/ 并登录,然后执行 `xhs login`
  340. - `NeedVerifyError` — 触发了验证码,请到浏览器中完成验证后重试
  341. - `IpBlockedError` — IP 被限制,尝试切换网络(手机热点或 VPN)
  342. - `SessionExpiredError` — Cookie 过期,执行 `xhs login` 刷新
  343. - 请求较慢是正常的 — 内置高斯随机延迟(~1-1.5s)是为了模拟人类浏览行为,避免触发风控
  344. ## 作为 AI Agent Skill 使用
  345. xiaohongshu-cli 自带 [`SKILL.md`](./SKILL.md),让 AI Agent 能自动学习并使用本工具。
  346. ### [Skills CLI](https://github.com/vercel-labs/skills)(推荐)
  347. ```bash
  348. npx skills add jackwener/xiaohongshu-cli
  349. ```
  350. | 参数 | 说明 |
  351. | --- | --- |
  352. | `-g` | 全局安装(用户级别,跨项目共享) |
  353. | `-a claude-code` | 指定目标 Agent |
  354. | `-y` | 非交互模式 |
  355. ### 手动安装
  356. ```bash
  357. mkdir -p .agents/skills
  358. git clone git@github.com:jackwener/xiaohongshu-cli.git .agents/skills/xiaohongshu-cli
  359. ```
  360. ### ~~OpenClaw / ClawHub~~(已过时)
  361. > ⚠️ ClawHub 安装方式已过时,不再支持。请使用上方的 Skills CLI 或手动安装。
  362. ## License
  363. Apache-2.0

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.