# Instagram API Python 教程：帳號、帖子、評論和 Reels 字幕（2026）

> Instagram 官方 API 能做什麼；再用 requests 寫一個 Python 指令碼，讀取任意公開帳號的資料、帖子、評論和 Reels 字幕：引數、翻頁和費用。

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

Instagram 官方 API 只服務你自己擁有或管理的專業帳號。要拿任意帳號的公開資料，按順序用四個介面：Instagram 帳號資訊、Instagram 帳號帖子、Instagram 帖子評論和 Instagram 影片字幕。下面的示例一共 8 次呼叫，最多花費 $0.032；請求到了平台的呼叫，返回為空、查不到或出錯也照常計費。

更新於 2026-11-12

Instagram 有官方 API，而且在某一類事情上就是最合適的工具。Meta 的 [Instagram Platform 概覽](https://developers.facebook.com/docs/instagram-platform/overview/)把它描述為一組面向 Instagram 專業帳號（即商家帳號和創作者帳號）的 API，帳號要麼是你自己擁有或管理的，要麼是登入了你的應用的使用者的。能做的事包括髮布內容、管理評論、收發私信和檢視資料洞察。對別人的帳號，它提供 [Business Discovery](https://developers.facebook.com/docs/instagram-platform/instagram-api-with-facebook-login/business-discovery/)，可以拿到其他專業帳號的基礎資訊和指標，有年齡限制的帳號則什麼都不返回。如果你要處理的是自己的帳號，就用 Meta 的官方 API。

這篇教程解決的是另一件事：用 Python、只靠 `requests`，讀取任意公開帳號的公開資料，比如競品、想合作的博主、在研究的品牌。最後每個帳號得到一個 JSON 檔案：帳號資料、最近的帖子和各項資料、討論最多的帖子下的評論，以及播放最多的 Reels 裡說了什麼，帶時間戳。

不需要登入 Instagram，不用建 Meta 應用，也不用 access token。每次呼叫就是帶著 key 發一個 HTTPS 請求。

## 分步操作

### 第一步：帳號資料

[Instagram 帳號資訊](https://okdata.online/zh/apis/instagram/users/get/)接收 `username`（帶不帶 @ 都行），返回一個帳號，每次 $0.004：`id`（數字帳號 ID）、`username`、`name`、`bio`、`followers`、`following`、`posts`、`verified` 和 `avatar_url`。加 `view=full` 還有 `ext.private`（是否私密）、`ext.website`、`ext.links`（簡介裡的連結）、`ext.category` 和 `ext.business`。`likes` 為 null，因為 Instagram 不顯示帳號的累計點贊。

```bash
curl -G "https://api.okdata.online/v1/instagram/users/get" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  -d username=northfieldbakery -d view=full
```

往下走之前先看 `ext.private`。私密帳號的資料能拿到，但它的帖子不公開。

### 第二步：帖子

[Instagram 帳號帖子](https://okdata.online/zh/apis/instagram/users/posts/list/)接收 `username` 和 `type`：`all`（預設，全部帖子）或 `reel`（只要 Reels，取自帳號的 Reels 標籤頁）。帖子從新到舊，每頁 12 條，每頁 $0.004。每條帖子有：

- `id`：短碼，也就是連結裡 `/p/` 或 `/reel/` 後面那一段，比如 `DQx7pLk2mVe`。評論和字幕介面都用它。
- `type`：Reels 和影片為 `video`，圖片和多圖帖為 `image`。
- `text`（文案）、`hashtags`、`images`、`published_at` 和 `url`。
- `metrics.likes`、`metrics.comments`，影片還有 `metrics.views`（播放數）。

加 `view=full` 會多出 `ext.duration_s`（時長）、`ext.coauthors`（合拍帖的其他作者）、`ext.product_type` 和 `ext.media_id`。要下一頁，就把 `page.next_cursor` 作為 `cursor` 傳回去；`page.has_more` 為 `false` 時停下。

```bash
curl -G "https://api.okdata.online/v1/instagram/users/posts/list" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  -d username=northfieldbakery -d type=all -d view=full
```

### 第三步：評論

[Instagram 帖子評論](https://okdata.online/zh/apis/instagram/posts/comments/list/)接收短碼 `id`，或者帖子連結 `url`。評論從新到舊，每頁約 15 條，每頁 $0.004。每條有 `id`、`text`、`author.username`、`likes`、`replies`（下面有幾條回覆）和 `published_at`；`author.name` 為 null。想看某條評論下的回覆，把它的 `id` 和帖子短碼（作為 `post_id`）傳給[Instagram 評論回覆](https://okdata.online/zh/apis/instagram/comments/replies/list/)。

```bash
curl -G "https://api.okdata.online/v1/instagram/posts/comments/list" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  -d id=DQx7pLk2mVe
```

### 第四步：Reels 裡說了什麼

[Instagram 影片字幕](https://okdata.online/zh/apis/instagram/posts/transcript/get/)接收短碼或連結，返回 Reel 或影片帖子裡說的話，每次 $0.004：帶 `start`、`end`（單位秒）的 `segments`，以及完整的 `text`。只處理兩分鐘以內的影片。`lang` 返回 `und`（未識別），語言要緊的話自己檢測一下。影片裡沒有人說話時返回 `not_found`，照常計費。

```bash
curl -G "https://api.okdata.online/v1/instagram/posts/transcript/get" \
  -H "Authorization: Bearer $OKDATA_API_KEY" \
  -d id=DRb3nVw8kQz
```

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

指令碼最多呼叫 8 次：1 次帳號資料、最多 3 頁帖子、2 頁評論、2 份字幕。每個邏輯請求都有自己的 `Idempotency-Key`，如果結果已經存下、只是網路斷了，重試會拿回那份結果，不會扣兩次錢。遇到 `rate_limited` 就等 `retry_after_seconds` 秒；其他錯誤直接帶著錯誤碼和資訊停下。

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

API = "https://api.okdata.online"
KEY = os.environ["OKDATA_API_KEY"]
USERNAME = "northfieldbakery"
POST_PAGES = 3      # 每頁 12 條帖子；每頁一次呼叫
COMMENT_POSTS = 2   # 評論最多的幾條帖子，各讀第一頁評論
TRANSCRIPTS = 2     # 兩分鐘以內、播放最多的幾條影片


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


def call(path, **params):
    headers = {"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())}
    for attempt in range(3):
        try:
            body = requests.get(API + path, headers=headers, params=params, timeout=90).json()
        except requests.RequestException:
            time.sleep(2 ** attempt)  # 重試沿用同一個 key：已存下的結果重放不扣費
            continue
        if body["code"] == "ok":
            return body
        if body["code"] == "rate_limited":
            time.sleep(body.get("retry_after_seconds") or 2)
            continue
        raise ApiError(body)
    raise RuntimeError(f"{path}: no answer after 3 attempts")


profile = call("/v1/instagram/users/get", username=USERNAME, view="full")["data"]["item"]
if profile["ext"]["private"]:
    raise SystemExit(f"@{USERNAME} is private; its posts are not public")

posts, cursor = [], None
for _ in range(POST_PAGES):
    body = call("/v1/instagram/users/posts/list", username=USERNAME, view="full", **({"cursor": cursor} if cursor else {}))
    posts += body["data"]["items"]
    if not body["page"]["has_more"]:
        break
    cursor = body["page"]["next_cursor"]

for post in sorted(posts, key=lambda p: p["metrics"]["comments"] or 0, reverse=True)[:COMMENT_POSTS]:
    post["comment_page"] = call("/v1/instagram/posts/comments/list", id=post["id"])["data"]["items"]

videos = [p for p in posts if p["type"] == "video" and (p["ext"]["duration_s"] or 0) <= 120]
for post in sorted(videos, key=lambda p: p["metrics"]["views"] or 0, reverse=True)[:TRANSCRIPTS]:
    try:
        post["transcript"] = call("/v1/instagram/posts/transcript/get", id=post["id"])["data"]["item"]
    except ApiError as err:
        if err.code != "not_found":  # 影片裡沒人說話：照常計費，跳過即可
            raise

with open(f"{USERNAME}.json", "w", encoding="utf-8") as f:
    json.dump({"profile": profile, "posts": posts}, f, ensure_ascii=False, indent=2)
print(profile["followers"], "followers;", len(posts), "posts saved")
```

想往前多翻，就調大 `POST_PAGES`：10 頁約 120 條帖子，光帖子就要 $0.04。

## 注意事項

- **短碼就是帖子 ID。** 所有帖子類介面都接收短碼作為 `id`，或者完整連結作為 `url`。別的工具要 Instagram 的數字媒體 ID 時，用 `ext.media_id`。
- **評論只能從新到舊。** 沒有按點贊排序的選項。想找最有共鳴的評論，多讀幾頁，自己按 `likes` 排。
- **哪些欄位是空的。** 帖子沒有 `title`；分享、收藏、轉發數為 null，因為 Instagram 不公開。只有影片有播放數。
- **只看 Reels。** `type=reel` 列的是 Reels 標籤頁。研究影片內容時用它，可以省下翻圖片帖的那些頁。
- **出錯和 `not_found` 也計費**：只要請求到了平台，已刪除的帖子、沒有人聲的影片都照常計費。引數錯誤和限流不扣費。
- **用官方 API 看別人的帳號。** Business Discovery 能拿到其他專業帳號的基礎資訊和指標。如果這些就夠用，而且你本來就有 Meta 應用，用它也很好。

要權衡 Meta 官方 API 和第三方 API 哪個更適合你的專案，看[官方 API 和第三方社媒資料怎麼選](https://okdata.online/zh/answers/official-api-vs-third-party-social-data/)。長期盯幾個帳號的做法，在[競品監控](https://okdata.online/zh/solutions/competitor-monitoring/)裡。

## 示例花費

一個帳號的資料、最近三頁帖子、評論最多的兩條帖子的第一頁評論，以及播放最多的兩條 Reels 的字幕

| 介面 | 呼叫次數 | 單價 | 小計 |
|---|---|---|---|
| [Instagram 帳號資訊](https://okdata.online/zh/apis/instagram/users/get/) | 1 | $0.004 | $0.004 |
| [Instagram 帳號帖子](https://okdata.online/zh/apis/instagram/users/posts/list/) | 3 | $0.004 | $0.012 |
| [Instagram 帖子評論](https://okdata.online/zh/apis/instagram/posts/comments/list/) | 2 | $0.004 | $0.008 |
| [Instagram 影片字幕](https://okdata.online/zh/apis/instagram/posts/transcript/get/) | 2 | $0.004 | $0.008 |
| 合計 | 8 |  | $0.032 |

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

## 在你的 AI 裡用（MCP）

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

可以這樣說：查一下 Instagram 帳號 northfieldbakery：粉絲數和簡介，最近 36 條帖子的點贊、評論和播放，評論最多的兩條帖子的第一頁評論，以及播放最多的兩條 Reels 裡說了什麼。總結一下它的粉絲最常問什麼。

```json
{
  "endpoint": "instagram.users.get",
  "params": {
    "username": "nasa"
  },
  "idempotency_key": "<新的 UUID>"
}
```

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

## 本指南用到的介面

- [Instagram 帳號資訊](https://okdata.online/zh/apis/instagram/users/get/) `instagram.users.get`：$0.004/次
- [Instagram 帳號帖子](https://okdata.online/zh/apis/instagram/users/posts/list/) `instagram.users.posts.list`：$0.004/次 · 每頁約 12 條帖子
- [Instagram 帖子評論](https://okdata.online/zh/apis/instagram/posts/comments/list/) `instagram.posts.comments.list`：$0.004/次 · 每頁約 15 條評論
- [Instagram 影片字幕](https://okdata.online/zh/apis/instagram/posts/transcript/get/) `instagram.posts.transcript.get`：$0.004/次

## 更多Instagram內容

- [Instagram API](https://okdata.online/zh/apis/instagram/)
- [Instagram API Python 教程：帳號、帖子、評論和 Reels 字幕（2026）](https://okdata.online/zh/guides/instagram-api-python/)
- [有沒有給 Claude 或 Cursor 用的 Instagram MCP 服務，能看主頁、Reels、評論和話題？](https://okdata.online/zh/answers/instagram-mcp-server-claude/)
- [怎麼找到某個細分領域的 Instagram 博主，並按粉絲數排序？](https://okdata.online/zh/answers/find-instagram-creators-by-niche/)
- [怎麼把 Instagram Reel 裡說的話轉成文字？](https://okdata.online/zh/answers/instagram-reel-transcript-api/)
- [按千次播放給剪輯手結算，怎麼統計 TikTok、YouTube Shorts、Instagram Reels 和 X 上每條切片的播放量？](https://okdata.online/zh/answers/clipper-payout-view-tracking/)
- [有沒有能讓 Cursor 搜 TikTok、Instagram 和 Reddit 的 MCP？](https://okdata.online/zh/answers/cursor-mcp-tiktok-instagram-reddit/)
- [不是自己管理的 Instagram 帳號，怎麼用 API 拿到帖子下的評論？](https://okdata.online/zh/answers/instagram-comments-api-other-accounts/)
- [評論介面](https://okdata.online/zh/roles/posts-comments-list/)
- [帳號資訊介面](https://okdata.online/zh/roles/accounts-get/)
- [帳號作品列表介面](https://okdata.online/zh/roles/accounts-posts-list/)
- [字幕介面](https://okdata.online/zh/roles/transcripts-get/)

## 資料來源

- [Instagram Platform overview](https://developers.facebook.com/docs/instagram-platform/overview/) (讀取於 2026-11-12)
- [Instagram API with Facebook Login: Business Discovery](https://developers.facebook.com/docs/instagram-platform/instagram-api-with-facebook-login/business-discovery/) (讀取於 2026-11-12)
