# 公眾號 API Python 教程：把文章轉成 Markdown 給 RAG 用（2026）

> 用 Python 寫一個小客戶端：按名稱找到公眾號，列出最近的文章，每篇存成帶 front matter 的 Markdown 檔案，直接拿去切塊和向量化。

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

微信官方介面只服務你自己管理的公眾號，所以對任意公開帳號，這篇教程用 Python 調 okdata 的三個介面：公眾號搜尋、公眾號歷史文章和公眾號文章詳情。示例一共 14 次呼叫，搜尋按滿頁計，花費 $0.84；請求到了平台的呼叫，返回為空、查不到或出錯也照常計費。

更新於 2026-11-12

微信官方介面能做什麼？公眾號的服務端介面都從 access_token 開始，它用公眾號的 AppID 和 AppSecret 換取，有效期 7200 秒。拿到它之後，釋出能力裡的 `freepublish_batchget` 能返回你這個號已經發布的文章，其他介面還能管理草稿、素材和看統計資料。第三方平台在公眾號授權之後，也能代它呼叫這些介面。所以如果號是你自己的，就用官方介面：免費、完整，還能拿到原始 HTML。它做不到的是讀你不管理的號，而做行業研究或競品知識庫，要的恰恰是這部分。

這篇教程講的就是這種情況。你會寫一個 Python 小客戶端：按名稱找到公眾號，列出最近的文章，拉每篇的全文，存成帶 YAML front matter 的 Markdown 檔案，開頭寫著標題、公眾號、日期和原文連結。這些檔案可以直接交給切塊和向量化流程，每個塊都能帶上出處。

## 分步操作

### 第一步：準備環境

需要 Python 3.9 以上、`requests`，以及放在環境變數裡的 key。沒有 SDK，也不用登入微信。

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

每次呼叫都是對 `https://api.okdata.online` 加介面路徑發 GET 請求，key 放在 Bearer 頭裡。成功時 `"code"` 為 `"ok"`；出錯時返回 `code`、`message`、`request_id` 和 `retry` 提示（`yes` 表示等 `retry_after_seconds` 後可以重試）。

### 第二步：找到公眾號

[公眾號搜尋](https://okdata.online/zh/apis/wechat_mp/accounts/search/)的 `query` 填公眾號名稱。每個結果有 `id`（原始 ID，`gh_…`）、`username`（微訊號）、`name` 和 `followers`。只保留 `name` 完全一致的那個：公眾號名稱不唯一，排第一的不一定是你要的號。

搜尋按返回的公眾號數計費：每個 $0.058，一次最多 $0.58。用完整名稱搜，通常只返回一個或幾個；一個都沒搜到，也按一個計費。第一次跑完就把 gh_ ID 存下來，以後這個號再也不用搜。

```bash
curl -G "https://api.okdata.online/v1/wechat_mp/accounts/search" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'query=少數派'
```

### 第三步：列出最近的文章

[公眾號歷史文章](https://okdata.online/zh/apis/wechat_mp/accounts/articles/list/)的 `id` 傳 gh_ ID 或微訊號，每次返回 10 篇，從新到舊，每次 $0.02。每篇有 `id`、`title`、`url`、`published_at` 和摘要 `text`。用 `cursor` 翻頁，直到 `page.has_more` 為 false 或者到了你設的頁數上限。

### 第四步：把每篇文章拉成文本

[公眾號文章詳情](https://okdata.online/zh/apis/wechat_mp/articles/get/)的 `url` 傳文章連結，`text` 裡是純文本正文，段落和小標題各佔一行，正文圖片已去掉，每次 $0.02。同時返回 `title`、`published_at` 和 `author`（公眾號的 gh_ ID 和名稱）。加 `view=full` 時，`ext.author_byline` 是署名作者，`ext.source_url` 是文末“閱讀原文”的連結（沒有就是 null）。

```bash
curl -G "https://api.okdata.online/v1/wechat_mp/articles/get" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'url=https://mp.weixin.qq.com/s/Vt8nR2kLq5XwJ0cYhPa3dE' \
  --data-urlencode 'view=full'
```

### 第五步：客戶端程式碼

下面的指令碼跑的就是示例：搜尋一次，最多讀 `MAX_PAGES` 頁歷史文章，把列出的所有文章寫進索引，再挑出最多 `MAX_ARTICLES` 篇本地還沒有的文章拉全文，存成 `kb/wechat/<id>.md`。下週再跑一次，只為新文章付錢。

```python
import os
import pathlib
import re
import time
import uuid
import requests

API = "https://api.okdata.online"
SESSION = requests.Session()
SESSION.headers["Authorization"] = f"Bearer {os.environ['OKDATA_API_KEY']}"
OUT = pathlib.Path("kb/wechat")
MAX_PAGES = 3      # 歷史文章頁數，每頁 10 篇
MAX_ARTICLES = 10  # 每次執行最多拉幾篇全文


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=90).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 find_account(name):
    accounts = call("/v1/wechat_mp/accounts/search", query=name)["data"]["items"]
    match = next((a for a in accounts if a["name"] == name), None)
    if match is None:
        raise SystemExit(f"no account named {name!r}; got {[a['name'] for a in accounts]}")
    return match


def history(account_id):
    cursor = None
    for _ in range(MAX_PAGES):
        body = call("/v1/wechat_mp/accounts/articles/list", id=account_id, **({"cursor": cursor} if cursor else {}))
        yield from body["data"]["items"]
        if not body["page"]["has_more"]:
            return
        cursor = body["page"]["next_cursor"]


def quoted(s):
    return '"' + (s or "").replace("\\", "\\\\").replace('"', '\\"') + '"'


def to_markdown(article, account):
    ext = article.get("ext", {})
    front = [
        "---",
        f"title: {quoted(article['title'])}",
        f"account: {quoted(account['name'])}",
        f"account_id: {account['id']}",
        f"byline: {quoted(ext.get('author_byline'))}",
        f"published: {article['published_at']}",
        f"source: {article['url']}",
        "---",
    ]
    return "\n".join(front) + f"\n\n# {article['title'] or ''}\n\n{article['text']}\n"


def main(name):
    OUT.mkdir(parents=True, exist_ok=True)
    account = find_account(name)
    listed = list(history(account["id"]))  # 從新到舊
    with open(OUT / "index.tsv", "w", encoding="utf-8") as f:
        f.writelines(f"{a['published_at']}\t{a['title']}\t{a['url']}\n" for a in listed)

    path_of = lambda a: OUT / (re.sub(r"[^\w-]", "_", a["id"]) + ".md")
    todo = [a for a in listed if not path_of(a).exists()][:MAX_ARTICLES]
    for a in todo:
        try:
            full = call("/v1/wechat_mp/articles/get", url=a["url"], view="full")["data"]["item"]
        except ApiError as err:
            if err.code == "not_found":  # 列出之後被刪了；照常計費，跳過即可
                continue
            raise
        path_of(a).write_text(to_markdown(full, account), encoding="utf-8")
        print("saved", full["title"])


if __name__ == "__main__":
    main("少數派")
```

第一次執行就是示例裡的 14 次呼叫：1 次搜尋、3 頁歷史文章、10 篇全文。如果要把這個號最近 300 篇都補齊，還要再花 $6.60。

### 第六步：切塊和入庫

每個檔案是 front matter 加正文。按空行把正文切成幾百字一塊，把 `title`、`account`、`published` 和 `source` 複製到每個塊的後設資料裡，這樣回答時能引用原文、附上鍊接。大多數載入器能直接讀 YAML front matter；讀不了的話，自己解析兩行 `---` 之間的內容即可。

## 注意事項

- **是文本，不是排版。** 詳情返回純文本，表格會變成一行行文字，正文圖片沒了，封面連結在 `images` 裡。要保留文章原本的樣子，得用別的辦法存 HTML。
- **轉載。** 很多號會轉載別人的文章。原創還是轉載的標記（`ext.copyright`）一般不帶，入庫前按內容去重更穩：標題相同，或 `text` 開頭一段相同，基本就是同一篇，免得重複內容干擾檢索。
- **刪掉的也計費。** 列出之後被刪的文章返回 `not_found`，照常計費，客戶端會直接跳過。
- **重試和 key。** 客戶端對同一個請求的重試沿用同一個 `Idempotency-Key`，24 小時內同樣的請求配同樣的 key，會拿回上次的結果，`meta.replayed` 為 `true`，不再扣費。平台出錯後的重試算一次新呼叫，照常計費。
- **文本不可信。** 文章是陌生人寫的，要告訴模型把檢索到的段落當資料看，不要當指令執行。
- **版權。** 只用於內部研究，每個塊都帶上原文連結，不要把整篇文章原樣返回給使用者。

只想看 Markdown 那一步的簡版，見[怎麼把公眾號文章轉成 RAG 能用的乾淨文本](https://okdata.online/zh/answers/wechat-articles-to-text-for-rag/)。手上只有名稱、要先查 ID，見[怎麼查公眾號的原始 ID](https://okdata.online/zh/answers/find-wechat-official-account-id/)。

## 示例花費

搜一次“少數派”，翻 3 頁歷史文章（約 30 篇），把最新的 10 篇存成 Markdown 檔案

| 介面 | 呼叫次數 | 單價 | 小計 |
|---|---|---|---|
| [公眾號搜尋](https://okdata.online/zh/apis/wechat_mp/accounts/search/) | 1 | $0.058 | $0.58 |
| [公眾號歷史文章](https://okdata.online/zh/apis/wechat_mp/accounts/articles/list/) | 3 | $0.02 | $0.06 |
| [公眾號文章詳情](https://okdata.online/zh/apis/wechat_mp/articles/get/) | 10 | $0.02 | $0.20 |
| 合計 | 14 |  | $0.84 |

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

## 在你的 AI 裡用（MCP）

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

可以這樣說：找到公眾號“少數派”，取它最新的 10 篇文章，每篇整理成 Markdown，開頭寫上標題、公眾號、釋出日期和原文連結。

```json
{
  "endpoint": "wechat_mp.accounts.search",
  "params": {
    "query": "36氪"
  },
  "idempotency_key": "<新的 UUID>"
}
```

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

## 本指南用到的介面

- [公眾號搜尋](https://okdata.online/zh/apis/wechat_mp/accounts/search/) `wechat_mp.accounts.search`：$0.058/條 · 每次最多 $0.58
- [公眾號歷史文章](https://okdata.online/zh/apis/wechat_mp/accounts/articles/list/) `wechat_mp.accounts.articles.list`：$0.02/次 · 每頁約 10 篇文章
- [公眾號文章詳情](https://okdata.online/zh/apis/wechat_mp/articles/get/) `wechat_mp.articles.get`：$0.02/次

## 更多微信公眾號內容

- [微信公眾號 API](https://okdata.online/zh/apis/wechat_mp/)
- [公眾號 API Python 教程：把文章轉成 Markdown 給 RAG 用（2026）](https://okdata.online/zh/guides/wechat-official-account-api-python/)
- [怎麼拿到一個公眾號的歷史文章和全文](https://okdata.online/zh/guides/wechat-official-account-articles/)
- [公眾號文章資料 API 多少錢？](https://okdata.online/zh/answers/wechat-official-account-api-price/)
- [為什麼 ChatGPT、Claude 打不開公眾號文章連結？怎麼讓 AI 讀到全文？](https://okdata.online/zh/answers/ai-read-wechat-article-link/)
- [怎麼不登入匯出一個公眾號的全部歷史文章？](https://okdata.online/zh/answers/export-wechat-official-account-articles/)
- [怎麼監控競品公眾號每天發了什麼？](https://okdata.online/zh/answers/monitor-competitor-wechat-official-accounts/)
- [公眾號文章連結裡的 __biz 是什麼？](https://okdata.online/zh/answers/wechat-biz-parameter/)
- [公眾號的原始 ID（gh_ 開頭）是什麼？](https://okdata.online/zh/answers/wechat-gh-original-id/)
- [平台官方 API 和第三方資料介面怎麼選（2026）](https://okdata.online/zh/compare/official-apis-vs-data-apis/)
- [社媒資料 MCP 伺服器：自己部署還是用託管的](https://okdata.online/zh/compare/social-media-data-mcp-servers/)
- [公眾號文章和閱讀數介面有哪些？官方介面、第三方 API、開源工具、資料平台 4 類方案怎麼選（2026）](https://okdata.online/zh/compare/wechat-article-data-apis/)
- [獲取微信公眾號資料的幾種辦法：官方介面、RSS 橋接和資料介面](https://okdata.online/zh/compare/wechat-official-account-data-apis/)
- [讓 AI 讀小紅書、抖音、公眾號的 MCP 有哪些？開源自部署、瀏覽器自動化、託管 3 類怎麼選（Claude、Cursor、豆包）](https://okdata.online/zh/compare/xiaohongshu-douyin-wechat-mcp-servers/)

## 資料來源

- [微信開放文件: 獲取介面呼叫憑據 (getAccessToken)](https://developers.weixin.qq.com/doc/subscription/api/base/api_getaccesstoken.html) (讀取於 2026-11-12)
- [微信開放文件: 獲取已釋出的訊息列表 (freepublish_batchget)](https://developers.weixin.qq.com/doc/subscription/api/public/api_freepublish_batchget.html) (讀取於 2026-11-12)
