# 怎麼把微博搜尋結果匯出成 Excel？

> 把一次微博關鍵詞搜尋變成 .xlsx 檔案：逐頁翻、16 位微博 ID 按文本儲存、時間換成北京時間、再補上作者資料。費用、程式碼和幾個坑。

網頁版：https://okdata.online/zh-hant/answers/weibo-search-export-excel/

**簡短回答：**用微博搜尋按關鍵詞逐頁翻，用 openpyxl 把每條微博寫成一行，微博 ID 和使用者 ID 按文本存，時間換成北京時間。每頁約 10 條，收費 $0.002，翻 30 頁（約 300 條）是 $0.06；再用微博帳號資訊介面補上 120 個作者的資料，合計 $0.30。

需求總是這一句：“把微博上大家怎麼聊露營裝備的，導一份 Excel 給我。”搜尋本身不難，難在表格：微博 ID 末位被改成 0，中文變成亂碼，時間全都差 8 小時。這裡用一個介面完成搜尋，再寫出一份開啟就能用的 .xlsx。

## 能匯出哪些列

[微博搜尋](/zh/apis/weibo/posts/search/)加上 `view=full` 後：

| 列 | 欄位 |
|---|---|
| 微博 ID（mid） | `id` |
| 連結 | `url`，格式是 weibo.com/uid/bid |
| 作者 UID、暱稱、粉絲數 | `author.id`、`author.name`、`author.followers` |
| 釋出時間 | `published_at`（UTC，要換成北京時間） |
| 正文 | `text` |
| 轉發、評論、點贊 | `metrics.reposts`、`metrics.comments`、`metrics.likes` |
| 影片播放量 | `metrics.views`，只有影片微博才有 |
| 微博顯示的 IP 屬地 | `ext.region` |
| 正文在搜尋結果裡被截斷 | `ext.is_long_text` |

分享數和收藏數微博不公開，返回 null，`meta.unavailable` 裡標的是 `platform`。想要作者的認證說明、微博總數這些，就把去重後的 `author.id` 拿去調[微博帳號資訊](/zh/apis/weibo/users/get/)。

## Excel 的三個坑

1. **長 ID。**微博 ID 是 16 位，Excel 只保留 15 位有效數字，`5249013377610245` 會變成 `5249013377610240`，顯示成 `5.24901E+15`。用開源微博爬蟲的人經常遇到這個問題。ID 要按文本寫入，用 openpyxl 時傳字串就行。
2. **編碼。**CSV 雙擊用 Excel 開啟，中文可能是亂碼，這也是爬蟲專案 issue 區裡的老問題。直接寫 .xlsx，就不存在這個問題。
3. **時區。**`published_at` 是 UTC。寫入之前換成北京時間（UTC+8），並在表頭註明。

## 費用

| 匯出規模 | 呼叫次數 | 費用 |
|---|---|---|
| 一頁，約 10 條 | 1 | $0.002 |
| 30 頁，約 300 條 | 30 | $0.06 |
| 再加 120 個作者資料 | 150 | $0.30 |

## 示例

裝好 `requests` 和 `openpyxl`，設好金鑰，然後：

```python
import os, requests
from datetime import datetime, timezone, timedelta
from openpyxl import Workbook

API = "https://api.okdata.online"
H = {"Authorization": f"Bearer {os.environ['OKDATA_API_KEY']}"}
BJ = timezone(timedelta(hours=8))
QUERY, MAX_PAGES = "露營 裝備", 30

def call(path, **params):
    body = requests.get(API + path, headers=H, params=params, timeout=60).json()
    if body["code"] != "ok":
        raise RuntimeError(f'{body["code"]}: {body["message"]}')
    return body

wb = Workbook()
ws = wb.active
ws.title = "微博"
ws.append(["mid", "連結", "uid", "作者", "粉絲數", "釋出時間（北京）", "正文",
           "轉發", "評論", "點贊", "播放", "IP 屬地", "正文被截斷"])
seen, cursor = set(), None
for _ in range(MAX_PAGES):
    params = {"query": QUERY, "sort": "latest", "view": "full"}
    if cursor:
        params["cursor"] = cursor
    body = call("/v1/weibo/posts/search", **params)
    for p in body["data"]["items"]:
        if p["id"] in seen:
            continue
        seen.add(p["id"])
        when = datetime.fromisoformat(p["published_at"].replace("Z", "+00:00")).astimezone(BJ)
        m, a = p["metrics"], p["author"]
        ws.append([p["id"], p["url"], a["id"], a["name"], a["followers"], when.replace(tzinfo=None),
                   p["text"], m["reposts"], m["comments"], m["likes"], m["views"],
                   p["ext"].get("region"), p["ext"].get("is_long_text")])
    if not body["page"]["has_more"]:
        break
    cursor = body["page"]["next_cursor"]

wb.save("微博-露營裝備.xlsx")  # ID 是按字串寫入的，16 位一位不少
```

要加一張“作者”表，就對每個去重後的 `author.id` 調一次 `/v1/weibo/users/get`，傳 `id=<uid>` 和 `view=full`，寫入 `name`、`followers`、`posts`、`verified`、`ext.verified_reason` 和 `ext.ip_location`。

## 限制

- 微博搜尋返回的是微博對這個關鍵詞排出來的結果，不是歷史上所有微博。想覆蓋得更全，就 `sort=hot` 和 `sort=latest` 各跑一遍，按 `id` 合併，做法見[怎麼採集某個話題的微博做輿情分析](/zh/answers/weibo-public-opinion-dataset/)。
- 標了 `ext.is_long_text` 的微博，拿到的是搜尋結果裡顯示的截斷正文。介面目錄裡沒有微博詳情介面，取不到全文。
- 全程不需要微博帳號或 cookie，見[不登入怎麼按關鍵詞搜微博](/zh/answers/weibo-search-without-cookie/)。只返回公開微博。

## 用到的介面

- [微博搜尋](https://okdata.online/zh/apis/weibo/posts/search/) `weibo.posts.search`：$0.002/次 · 每頁約 10 條帖子
- [微博帳號資訊](https://okdata.online/zh/apis/weibo/users/get/) `weibo.users.get`：$0.002/次

## 更多微博內容

- [微博 API](https://okdata.online/zh/apis/weibo/)
- [微博 API Python 教程：關鍵詞搜尋、使用者資料和熱搜（2026）](https://okdata.online/zh/guides/weibo-api-python/)
- [微博和 B 站評論的 IP 屬地，能通過介面拿到嗎？](https://okdata.online/zh/answers/weibo-bilibili-ip-location-data/)
- [怎麼找某個領域的微博博主（KOL）？](https://okdata.online/zh/answers/weibo-find-kols-in-niche/)
- [2026 年微博還有能讀微博內容的開放 API 嗎？](https://okdata.online/zh/answers/weibo-official-api-2026/)
- [做輿情分析，怎麼批次採集某個話題的微博？](https://okdata.online/zh/answers/weibo-public-opinion-dataset/)
- [怎麼把微博搜尋結果匯出成 Excel？](https://okdata.online/zh/answers/weibo-search-export-excel/)
- [微博的 uid、mid 和 bid 分別是什麼？](https://okdata.online/zh/answers/weibo-uid-mid-bid/)
- [帳號資訊介面](https://okdata.online/zh/roles/accounts-get/)
- [內容搜尋介面](https://okdata.online/zh/roles/posts-search/)
- [微博熱搜：今日榜單](https://okdata.online/zh/tools/hot-search/weibo/)

## 資料來源

- [Microsoft 支援：在 Excel 中保留前導零和大數字](https://support.microsoft.com/en-us/excel/keeping-leading-zeros-and-large-numbers) (讀取於 2026-11-12)
- [openpyxl 文件](https://openpyxl.readthedocs.io/en/stable/) (讀取於 2026-11-12)
- [dataabc/weibo-search issue 208：Excel 裡的微博 id 顯示成 4.75E+15](https://github.com/dataabc/weibo-search/issues/208) (讀取於 2026-11-12)
- [dataabc/weiboSpider issue 565：寫入 CSV 時出現亂碼](https://github.com/dataabc/weiboSpider/issues/565) (讀取於 2026-11-12)

這個問題出現過的地方（讀取於 2026-11-12）：

- https://github.com/dataabc/weibo-search/issues/208
- https://github.com/dataabc/weiboSpider/issues/565
- https://www.v2ex.com/t/389043

更新於 2026-11-12
