# 小紅書 API Python 教程：筆記、博主和評論（2026）

> 用 Python 讀小紅書公開資料：筆記搜尋、筆記詳情、博主資訊、博主筆記列表和評論，附帶翻頁、重試和跑一遍的花費。

網頁版：https://okdata.online/zh-hant/guides/xiaohongshu-api-python/

小紅書官方開放平台是給店鋪用的，不能讀公開筆記，所以這篇教程用 requests 直接調 okdata 的五個介面：小紅書筆記搜尋、筆記詳情、博主資訊、博主筆記列表和筆記評論。示例一共 5 次呼叫，花費 $0.155；請求到了平台的呼叫，返回為空、查不到或出錯也照常計費。

更新於 2026-11-12

小紅書有沒有官方 API 能幹這件事？小紅書確實有開放平台，但那是電商開放平台：一類是店鋪授權後使用的工具型應用（ERP、打單、上貨、進銷存），一類是店鋪給自己系統做對接的自用型應用。蒲公英和廣告工具服務的是投放自己專案的廣告主。這些渠道都沒有提供“搜尋所有人的筆記”或“讀別人筆記下的評論”的介面，每個渠道具體能做什麼，見[小紅書有沒有官方 API](https://okdata.online/zh/answers/xiaohongshu-official-api/)。

另一個坎是 token。小紅書自己的網頁介面會給展示出來的每篇筆記附一個 `xsec_token`，開啟筆記時會校驗它，所以指令碼手裡只有筆記 ID 時經常被拒。原理見 [xsec_token 那篇問答](https://okdata.online/zh/answers/xiaohongshu-xsec-token/)。用下面這些介面，只傳 ID 或連結，不用管 token、Cookie 和簽名。

最後你會得到一個能複用的 Python 小客戶端：一個負責報錯和重試的函式、一個帶頁數上限的翻頁器、五個介面，以及一份 JSON 報告。

## 分步操作

### 第一步：準備環境

需要 Python 3.9 以上、`requests`，以及放在環境變數裡的 key。沒有 SDK 要裝。

```bash
pip install requests
export OKDATA_API_KEY=okd_...
```

每次呼叫都是對 `https://api.okdata.online` 加介面路徑發 GET 請求，key 放在 Bearer 頭裡。成功時 `"code"` 為 `"ok"`，資料在 `data` 裡（列表介面是 `data.items` 加 `page`，單個物件是 `data.item`）。出錯時返回 `code`、`message`、`request_id` 和 `retry` 提示：`yes` 表示稍後可以重試，有 `retry_after_seconds` 就按它等。

### 第二步：搜尋筆記

[小紅書筆記搜尋](https://okdata.online/zh/apis/xiaohongshu/notes/search/)接收 `query`、`sort`（`general`、`latest` 或 `popular`）和 `type`（`all`、`video` 或 `image`）。一次呼叫返回約 20 篇筆記，每次 $0.035，每篇有 `id`、`title`、`text` 的開頭部分、`author`、`published_at`、`hashtags` 和 `metrics`（點贊、收藏、評論、分享）。

```bash
curl -G "https://api.okdata.online/v1/xiaohongshu/notes/search" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'query=防曬霜' \
  --data-urlencode 'sort=popular'
```

### 第三步：拉一篇筆記的全文

[小紅書筆記詳情](https://okdata.online/zh/apis/xiaohongshu/notes/get/)接收 `id`（24 位十六進位制）或 `url`（筆記連結或 xhslink 分享連結），返回全文、全部圖片（影片筆記只給封面）、話題和最新資料，每次 $0.035。加 `view=full` 時，`ext.xsec_token` 裡是小紅書給這篇筆記附的 token，想拼一個能在瀏覽器裡開啟的連結時用得上。

```bash
curl -G "https://api.okdata.online/v1/xiaohongshu/notes/get" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'url=https://www.xiaohongshu.com/explore/672a4f1d000000001b03c58e'
```

### 第四步：作者的主頁資訊

[小紅書博主資訊](https://okdata.online/zh/apis/xiaohongshu/users/get/)的 `id` 傳使用者 ID（就是筆記的 `author.id`），或者 `url` 傳主頁連結，每次 $0.02。返回 `followers`、`following`、`posts`（筆記數）、`likes`（獲贊與收藏，和主頁上的口徑一致）、`bio`、`verified`，以及小紅書號 `username`。加 `view=full` 時，`ext.ip_location` 是主頁上顯示的屬地。

### 第五步：作者的筆記列表

[小紅書博主筆記列表](https://okdata.online/zh/apis/xiaohongshu/users/notes/list/)必須傳使用者 ID 作為 `id`，一次返回約 20 篇，從新到舊，每次 $0.03。這裡每篇筆記的 `author` 只有 ID，因為查的就是這個帳號。

### 第六步：筆記下的評論

[小紅書筆記評論](https://okdata.online/zh/apis/xiaohongshu/notes/comments/list/)必須傳筆記 `id`，一次返回約 10 條一級評論，每次 $0.035，每條有 `text`、`author`、`likes`、`replies`、`published_at` 和 `ip_location`。

```bash
curl -G "https://api.okdata.online/v1/xiaohongshu/notes/comments/list" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'id=672a4f1d000000001b03c58e'
```

### 第七步：完整指令碼

指令碼跑的就是上面的示例，結果寫進 `xhs_report.json`。`call` 對同一個請求的多次重試沿用同一個 `Idempotency-Key`。限流那次不扣費；平台出錯後的重試算新呼叫，會再計費一次。`pages` 給每個列表設了頁數上限，也就等於給花費設了上限。

```python
import json
import os
import time
import uuid
import requests

API = "https://api.okdata.online"
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {os.environ['OKDATA_API_KEY']}"
COMMENT_PAGES = 1   # 每頁一次呼叫
AUTHOR_PAGES = 1


class ApiError(Exception):
    def __init__(self, body):
        super().__init__(f"{body['code']}: {body['message']} (request {body['request_id']})")
        self.code = body["code"]


def call(path, **params):
    key = str(uuid.uuid4())  # 重試沿用同一個 key；平台出錯後的重試照常計費
    for attempt in range(3):
        body = SESSION.get(API + path, params=params, headers={"Idempotency-Key": key}, timeout=60).json()
        if body["code"] == "ok":
            return body
        if body.get("retry") == "yes" and attempt < 2:
            time.sleep(body.get("retry_after_seconds") or 5)
            continue
        raise ApiError(body)


def pages(path, max_pages, **params):
    """逐頁返回結果；到 max_pages 或 has_more 為 false 時停。"""
    cursor = None
    for _ in range(max_pages):
        body = call(path, **params, **({"cursor": cursor} if cursor else {}))
        yield from body["data"]["items"]
        if not body["page"]["has_more"]:
            return
        cursor = body["page"]["next_cursor"]


found = call("/v1/xiaohongshu/notes/search", query="防曬霜", sort="popular")["data"]["items"]
if not found:
    raise SystemExit("no notes for that query")
top = max(found, key=lambda n: n["metrics"]["likes"] or 0)

note = call("/v1/xiaohongshu/notes/get", id=top["id"])["data"]["item"]
author = call("/v1/xiaohongshu/users/get", id=note["author"]["id"])["data"]["item"]
recent = list(pages("/v1/xiaohongshu/users/notes/list", AUTHOR_PAGES, id=author["id"]))
comments = list(pages("/v1/xiaohongshu/notes/comments/list", COMMENT_PAGES, id=note["id"]))

report = {
    "note": {"id": note["id"], "title": note["title"], "text": note["text"], "images": note["images"],
             "likes": note["metrics"]["likes"], "saves": note["metrics"]["favorites"],
             "comments": note["metrics"]["comments"], "published_at": note["published_at"]},
    "author": {"id": author["id"], "name": author["name"], "followers": author["followers"],
               "notes": author["posts"], "likes_and_saves": author["likes"]},
    "recent_notes": [{"id": n["id"], "title": n["title"], "published_at": n["published_at"],
                      "likes": n["metrics"]["likes"]} for n in recent],
    "comments": [{"text": c["text"], "likes": c["likes"], "replies": c["replies"],
                  "ip_location": c["ip_location"]} for c in comments],
}
with open("xhs_report.json", "w", encoding="utf-8") as f:
    json.dump(report, f, ensure_ascii=False, indent=2)
```

要擴大規模，就調高上限、多迴圈幾篇筆記。20 篇筆記拉全文、每篇讀 3 頁評論，是 $2.80。

## 注意事項

- **沒有瀏覽量。** 小紅書公開筆記不顯示瀏覽數，所以 `metrics.views` 為 null，`meta.unavailable` 裡的原因是 `platform`。排序時看收藏（`favorites`）和評論數。
- **一個人有兩種 ID。** 帳號類介面要的是使用者 ID（24 位十六進位制），大家互相分享的是 `username` 裡的小紅書號。主頁連結和分享連結都可以當 `url` 傳。
- **刪掉或私密的也計費。** 已經不存在的筆記或帳號返回 `not_found`，照常計費。指令碼會丟擲帶這個 code 的 `ApiError`，批次跑時捕獲後跳過即可。
- **評論數對不上。** 筆記上的評論數包含樓中樓回覆，評論介面列的是一級評論，每條附帶回複數。
- **時間是 UTC。** 所有 `published_at` 都是 UTC 的 ISO 8601 格式。
- **不讀的欄位可以不要。** `fields=id,title,metrics.likes` 只保留這幾個欄位，`view=compact` 每個物件返回更少欄位。兩者都不影響價格，但交給模型讀時返回更短。

要按關鍵詞批次匯出評論，看分步教程[按關鍵詞批次匯出小紅書評論](https://okdata.online/zh/guides/xiaohongshu-note-comments/)，從一次搜尋直接到 CSV。搜尋量大時怎麼算錢，見[小紅書筆記搜尋 API 多少錢](https://okdata.online/zh/answers/xiaohongshu-note-search-api-price/)。

## 示例花費

搜一次“防曬霜”，拉點贊最多那篇筆記的全文、作者資訊和最新筆記，再讀這篇筆記下第一頁評論

| 介面 | 呼叫次數 | 單價 | 小計 |
|---|---|---|---|
| [小紅書筆記搜尋](https://okdata.online/zh/apis/xiaohongshu/notes/search/) | 1 | $0.035 | $0.035 |
| [小紅書筆記詳情](https://okdata.online/zh/apis/xiaohongshu/notes/get/) | 1 | $0.035 | $0.035 |
| [小紅書博主資訊](https://okdata.online/zh/apis/xiaohongshu/users/get/) | 1 | $0.02 | $0.02 |
| [小紅書博主筆記列表](https://okdata.online/zh/apis/xiaohongshu/users/notes/list/) | 1 | $0.03 | $0.03 |
| [小紅書筆記評論](https://okdata.online/zh/apis/xiaohongshu/notes/comments/list/) | 1 | $0.035 | $0.035 |
| 合計 | 5 |  | $0.155 |

按本頁生成時的價格計算。請求到了平台的呼叫，返回為空或出錯也照常計費。

## 在你的 AI 裡用（MCP）

先接好 MCP 服務，然後直接說你要什麼。智慧體會自己找到這些介面、看清價格，再用你的餘額呼叫。

可以這樣說：在小紅書按最熱搜“防曬霜”，開啟點贊最多的那篇筆記看全文，查一下作者的主頁資訊和最近發的筆記，再讀這篇筆記下第一頁評論，告訴我評論區大家在問什麼。

```json
{
  "endpoint": "xiaohongshu.notes.search",
  "params": {
    "query": "防曬霜 推薦"
  },
  "idempotency_key": "<新的 UUID>"
}
```

MCP：`https://api.okdata.online/mcp`

## 本指南用到的介面

- [小紅書筆記搜尋](https://okdata.online/zh/apis/xiaohongshu/notes/search/) `xiaohongshu.notes.search`：$0.035/次 · 每頁約 20 篇筆記
- [小紅書筆記詳情](https://okdata.online/zh/apis/xiaohongshu/notes/get/) `xiaohongshu.notes.get`：$0.035/次
- [小紅書博主資訊](https://okdata.online/zh/apis/xiaohongshu/users/get/) `xiaohongshu.users.get`：$0.02/次
- [小紅書博主筆記列表](https://okdata.online/zh/apis/xiaohongshu/users/notes/list/) `xiaohongshu.users.notes.list`：$0.03/次 · 每頁約 20 篇筆記
- [小紅書筆記評論](https://okdata.online/zh/apis/xiaohongshu/notes/comments/list/) `xiaohongshu.notes.comments.list`：$0.035/次 · 每頁約 10 條評論

## 更多小紅書內容

- [小紅書 API](https://okdata.online/zh/apis/xiaohongshu/)
- [小紅書 API Python 教程：筆記、博主和評論（2026）](https://okdata.online/zh/guides/xiaohongshu-api-python/)
- [怎麼按關鍵詞批次匯出小紅書評論](https://okdata.online/zh/guides/xiaohongshu-note-comments/)
- [怎麼在小紅書蒲公英按報價和閱讀量篩達人](https://okdata.online/zh/guides/xiaohongshu-pgy-creator-rates/)
- [怎麼搜尋小紅書筆記並匯出成 CSV 表格](https://okdata.online/zh/guides/xiaohongshu-search-export-notes/)
- [有沒有不用掃碼登入的小紅書 MCP？](https://okdata.online/zh/answers/xiaohongshu-mcp-qr-login-expires/)
- [千問裡怎麼拿到抖音、小紅書、公眾號的資料？](https://okdata.online/zh/answers/qwen-douyin-xiaohongshu-data/)
- [騰訊元寶能讀抖音、小紅書的資料嗎？](https://okdata.online/zh/answers/yuanbao-douyin-xiaohongshu-data/)
- [怎麼在 Cursor 或 Cline 裡接入小紅書資料的 MCP？](https://okdata.online/zh/answers/cursor-cline-xiaohongshu-mcp/)
- [小紅書返回 300011 帳號異常，怎麼繼續採集筆記？](https://okdata.online/zh/answers/xiaohongshu-300011-account-abnormal/)
- [怎麼在小紅書上找到使用者對某個品牌的吐槽和差評？](https://okdata.online/zh/answers/xiaohongshu-brand-complaints/)
- [自己爬還是按次呼叫資料介面：成本、維護和風險](https://okdata.online/zh/compare/scraping-vs-data-api/)
- [怎麼選社交媒體資料 API（2026）](https://okdata.online/zh/compare/social-media-data-apis/)
- [社媒資料 MCP 伺服器：自己部署還是用託管的](https://okdata.online/zh/compare/social-media-data-mcp-servers/)

## 資料來源

- [小紅書電商開放平台](https://open.xiaohongshu.com/) (讀取於 2026-11-12)
