給 AI

操作指南

B站 API Python 教程:搜尋、影片資料、評論和熱門榜(2026)

四個介面:B站影片搜尋、按 BV 號取影片詳情、影片評論和熱門榜,每個都是帶 API key 的普通 GET 請求,不用 wbi 簽名,也不用 buvid3 Cookie。下面的示例一共 7 次呼叫,花費 $0.014;請求到了平台的呼叫,返回為空、查不到或出錯也照常計費。

更新於

用 Python 拿 B站資料,大多數程式碼是直接調 B站網頁自己的介面,能用,直到某天不能用。搜尋要 wbi 簽名,還要新鮮的 buvid3 Cookie,金鑰會輪換,跑了幾週的指令碼某天開始只返回 -412。這類程式碼大多參考的兩個社群專案,bilibili-API-collect 文件和 bilibili-api 這個 Python 庫,在 GitHub 上都已經歸檔、不再維護,下一次介面變動不會再有人從那邊修。如果你已經撞上 -412,可以先看B站搜尋介面一直返回 -412 怎麼辦。

這篇用 API key 做同樣幾件事:搜影片、按 BV 號讀一條影片的資料、翻評論、讀熱門榜。每次呼叫就是一個 HTTPS GET,沒有簽名程式碼、Cookie 或登入態要維護,依賴只有 requests。最後得到一個影片資料 CSV 和一個評論 CSV。

分步操作

先設好 key:export OKDATA_API_KEY=okd_...。每次返回都有 code(成功為 "ok");列表結果在 data.items,翻頁資訊在 page;單個物件在 data.item。

先說 ID:B站每條影片都有 BV 號,就是連結裡 BV1 開頭那段,比如 https://www.bilibili.com/video/BV1Gc411K7wD。下面四個介面用的 id 都是它。老的數字 AV 號還在,返回在 ext.aid 裡。各項資料分別在哪個欄位,見按 BV 號查播放、投幣和彈幕數。

第一步:搜影片

B站影片搜尋有 query 和 sort 兩個引數,sort 可選 relevance(預設,綜合)、latest(最新)或 most_viewed(最多播放)。一次呼叫返回約 20 條影片,每次 $0.002。每條有 id(BV 號)、title、簡介 text、published_at、author 下的 UP 主暱稱和數字 ID(mid)、hashtags 裡的標籤,以及 metrics.views、metrics.likes、metrics.comments 和 metrics.favorites。加上 view=full 還有 ext.danmaku、ext.duration 和 ext.section。

curl -G "https://api.okdata.online/v1/bilibili/videos/search" -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'query=相機推薦' --data-urlencode 'sort=most_viewed' --data-urlencode 'view=full'

第二步:讀一條影片的完整資料

B站影片詳情的 id 填 BV 號,或者用 url 傳完整連結,每次 $0.002。詳情補上了搜尋裡沒有的東西:metrics.shares,以及 view=full 時的 ext.coins、ext.danmaku、ext.aid、ext.cid、ext.duration_s 和 ext.section。投幣值得單獨一列:觀眾得花幣才能投,比點贊更能說明大家對這條影片的認可。

curl -G "https://api.okdata.online/v1/bilibili/videos/get" -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'id=BV1Gc411K7wD' --data-urlencode 'view=full'

第三步:翻評論

B站影片評論的 id 填 BV 號,sort 可選 hot(預設,最熱)或 latest(最新)。每頁約 20 條,每次 $0.002,每條有 text、author.name、author.id(評論者的 mid)、likes、replies、published_at 和 ip_location(IP 屬地,已去掉字首)。下一頁就把 page.next_cursor 作為 cursor 傳回去。

curl -G "https://api.okdata.online/v1/bilibili/videos/comments/list" -H "Authorization: Bearer $OKDATA_API_KEY" \
  --data-urlencode 'id=BV1Gc411K7wD' --data-urlencode 'sort=hot'

第四步:讀熱門榜

B站熱門榜沒有引數,返回當前的綜合熱門,每次約 50 行,每次 $0.002。每行有 rank、name(影片標題)、heat(播放量)和 url(影片連結,末尾就是 BV 號)。想看更多屏,熱門榜也可以用 cursor 翻頁。

curl -G "https://api.okdata.online/v1/bilibili/trends/list" -H "Authorization: Bearer $OKDATA_API_KEY"

第五步:完整指令碼

輔助函式檢查 body["code"],跳過已刪除的影片,遇到限流或平台繁忙就用同一個 Idempotency-Key 重試。限流那次不扣費;平台繁忙後的重試算新呼叫,會再計費一次。翻頁用一個帶頁數上限的生成器。

import csv
import os
import time
import uuid

import requests

API = "https://api.okdata.online"
KEY = os.environ["OKDATA_API_KEY"]
QUERY = "相機推薦"
TOP_VIDEOS = 2      # 查幾條影片詳情
COMMENT_PAGES = 3   # 第一條影片讀幾頁評論;每頁一次呼叫


def call(path, **params):
    headers = {"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())}
    for attempt in range(4):
        body = requests.get(API + path, headers=headers, params=params, timeout=60).json()
        if body["code"] == "ok":
            return body
        if body["code"] == "not_found":
            return None  # 已刪除或不公開:照常計費,跳過即可
        if body.get("retry") in ("yes", "same_key"):
            time.sleep(body.get("retry_after_seconds") or 2 ** attempt)
            continue
        raise RuntimeError(f"{body['code']}: {body['message']} (request {body['request_id']})")
    raise RuntimeError(f"{path}: 重試 4 次仍然失敗")


def paged(path, max_pages, **params):
    cursor = None
    for _ in range(max_pages):
        body = call(path, **params, **({"cursor": cursor} if cursor else {}))
        if body is None:
            return
        yield from body["data"]["items"]
        if not body["page"]["has_more"]:
            return
        cursor = body["page"]["next_cursor"]


board = call("/v1/bilibili/trends/list")["data"]["items"]
for row in board[:5]:
    print(row["rank"], row["heat"], row["name"], row["url"])

hits = call("/v1/bilibili/videos/search", query=QUERY, sort="most_viewed")["data"]["items"]
videos = []
for hit in hits[:TOP_VIDEOS]:
    body = call("/v1/bilibili/videos/get", id=hit["id"], view="full")
    if body:
        videos.append(body["data"]["item"])

with open("bilibili_videos.csv", "w", newline="", encoding="utf-8-sig") as f:
    out = csv.writer(f)
    out.writerow(["bvid", "title", "uploader", "views", "likes", "coins", "favorites", "shares", "danmaku", "published_at"])
    for v in videos:
        m, ext = v["metrics"], v["ext"]
        out.writerow([v["id"], v["title"], v["author"]["name"], m["views"], m["likes"], ext.get("coins"),
                      m["favorites"], m["shares"], ext.get("danmaku"), v["published_at"]])

if videos:
    first = videos[0]["id"]
    with open("bilibili_comments.csv", "w", newline="", encoding="utf-8-sig") as f:
        out = csv.writer(f)
        out.writerow(["bvid", "comment_id", "text", "user", "likes", "replies", "ip_location", "published_at"])
        for c in paged("/v1/bilibili/videos/comments/list", COMMENT_PAGES, id=first, sort="hot"):
            out.writerow([first, c["id"], c["text"], c["author"]["name"], c["likes"], c["replies"], c["ip_location"], c["published_at"]])

跑一遍就是上面的示例,7 次呼叫。如果要長期跟蹤,花費主要在詳情呼叫上:每天早上重新整理 500 個 BV 號、連續一個月,是 15,000 次呼叫,$30.00。

注意事項

  • 搜尋深度。 B站自己的搜尋翻到一定頁數就不再給結果,這個介面也一樣。話題比較寬的話,拆成幾個更具體的關鍵詞分別搜。
  • null 欄位。 搜尋結果沒有分享數(搜尋裡 metrics.shares 是 null,詳情裡有)。作品裡 UP 主的粉絲數是 null,目錄裡目前也還沒有 B站帳號介面。每個 null 欄位都在 meta.unavailable 裡註明。
  • 評論和回覆。 能拿到每條評論的回覆數,拿不到回覆正文。彈幕內容也拿不到,只有彈幕數。
  • 多 P 影片。 所有分 P 共用一個 BV 號,資料是整條影片的,ext.cid 是第一 P 的。
  • 資料是快照。 數字是呼叫那一刻讀到的,跟蹤增長時把 meta.fetched_at 一起存下來。
  • 哪些計費。 已刪除的影片返回 not_found,和空結果、平台出錯一樣,請求到了平台就照常計費。引數錯誤和限流不扣費。

不寫程式碼只想看榜,開啟 B站熱門榜工具就行。要跨平台研究一個話題,可以看內容調研,裡面講了搜尋、詳情和評論怎麼配合。

示例花費

按播放量搜一次“相機推薦”,取前 2 條影片的完整資料,讀第一條下 3 頁熱門評論,再讀一次熱門榜

介面呼叫次數單價小計
B站影片搜尋1$0.002$0.002
B站影片詳情2$0.002$0.004
B站影片評論3$0.002$0.006
B站熱搜榜1$0.002$0.002
合計7$0.014

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

在你的 AI 裡用(MCP)

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

可以這樣說在 B站按播放量搜“相機推薦”,給我前 2 條影片的播放、點贊、投幣、收藏、分享和彈幕數,再看第一條下面的熱門評論。順便看看現在熱門榜上有什麼。

智慧體第一次呼叫 call 工具時傳送的內容
{
  "endpoint": "bilibili.videos.search",
  "params": {
    "query": "Claude Code 教程"
  },
  "idempotency_key": "<新的 UUID>"
}

配置 MCP 服務 →

資料來源

  1. bilibili-API-collect 倉庫(GitHub,已歸檔)github.com · 讀取於
  2. bilibili-api Python 庫倉庫(GitHub,已歸檔)github.com · 讀取於

接上一次,之後直接問 AI。

新金鑰附 $0.20 試用額度。貼一句話給你的 AI,它就會自己接好。

免費開始
一句話接到你的 AI

把這句話貼給你的 AI

讀一下 https://okdata.online/zh/agents.md,幫我把 okdata 設定好;我的金鑰在環境變數 OKDATA_API_KEY 裡。

Claude Code、Cursor、Codex 等能開啟網址的 AI 代理,讀完會自己設定好。

MCP 網址https://api.okdata.online/mcp