用 Python 回填历史推文:按日期范围导出 X(Twitter)帖子
Python 教程:导出某个查询在两个日期之间匹配到的 X(Twitter)帖子,最早可到 2006 年。使用精确的 Unix 时间边界、分窗口翻页、空页重试和断点续跑。
本指南用 Python 导出 X(Twitter)的历史帖子:某个查询在两个日期之间匹配到的公开帖子,保存为 JSON Lines 文件,可以直接用 pandas 或 DuckDB 读取。搜索最早可以追溯到 2006 年 3 月。在较长的时间范围上,简单的搜索循环会悄悄漏掉帖子,所以下面每一步都会说明不这样做会出什么问题。对于热门关键词,帖子发布约一周后,搜索就只能返回其中一部分,详见下文。本页所有查询和数字都是 2026 年 11 月 28 日在线上搜索 API 实测得到的。
准备
- 在 twexapi.io 注册账号,获得 20,000 免费 Credits,约可获取 4,000 条帖子。
- 在控制台复制 API Key 并设置为环境变量:
export TWEXAPI_KEY="twexapi_xxx"
pip install requests
1. 用 Unix 秒数限定每个查询的时间范围
高级搜索接口支持 X 的日期运算符,但 X 对其中一些处理得比较宽松。请使用 since_time: 和 until_time: 加 Unix 秒数,它们在 2006 年到 2026 年的帖子上都是精确的。
| 查询 | 结果 |
|---|---|
from:NASA since:2020-01-07 until:2020-01-08 |
第一页就出现了 1 月 9 日的帖子 |
from:NASA since:2020-01-07_00:00:00_JST until:2020-01-08_00:00:00_JST |
NASA 那天(日本时间)发了 16 条,只返回 11 条;日本时间 9 之前的 5 条缺失 |
from:NASA since_time:1578322800 until_time:1578409200(同一个日本时间日) |
16 条全部返回,3 次运行都一样 |
from:NASA since:2026-11-25_17:00:00_UTC until:2026-11-25_18:00:00_UTC |
3 次运行中有 2 次什么都没返回,而 NASA 在这一小时里发了 2 条 |
把 UTC 日期转换成 Unix 秒数:
from datetime import datetime, timezone
int(datetime(2015, 1, 1, tzinfo=timezone.utc).timestamp()) # 1420070400
2. 把时间范围切成窗口,在窗口内跟随游标
长时间范围需要翻几百页,而两种最直接的翻页方式都漏了帖子。我们在 from:NASA 2015 年 1 月到 3 月上做了测试,所有运行合起来共找到 1,492 条帖子:
- 整个范围只跟一个游标:返回 1,368 条,NASA 1 月的 506 条只拿到 401 条。
- 用
max_id:翻页(把max_id:设为已保存的最旧帖子 ID 减一):返回 1,484 条。搜索结果页并不严格按从新到旧排列:一页里可能有较旧的帖子,却漏掉较新的帖子,而max_id:会把这些较新的帖子永久跳过。
效果最好的做法是每个查询只覆盖一个短窗口,并用 next_cursor 翻页,直到这个窗口翻完。用一天一个窗口,同样的三个月在一次运行中返回了 1,483 条,漏掉了 1 月 6 日连续的 7 条和 1 月 27 日的 2 条。与另一次运行(它漏掉了另外两天)合并后,得到了全部 1,492 条。账号或冷门关键词用一天的窗口,热门关键词用 10 分钟的窗口:bitcoin 的一个 10 分钟窗口就有 341 条帖子。
3. 遇到空页要重试
搜索有时会在后面还有帖子时返回空页。在把窗口当作翻完之前,请用同一个游标再请求一次同一页。在 bitcoin 的 1 分钟窗口测试中,10 个窗口里有 4 个在空页之后重试又拿到了更多帖子。在一次只重试一次的 from:NASA 2015 年 1 月到 3 月的运行中,有两天返回为空,而 NASA 那两天分别发了 5 条和 15 条。
下面的脚本最多再请求 3 次,分别等待 2、4、8 秒。窗口的最后一页是空页,所以每个窗口结尾都有 4 个空页:除了帖子本身,还要多花 20 Credits 和约 14 秒。窗口不要切得比需要的更小。
4. 回填脚本
脚本按窗口从旧到新遍历整个范围,每个窗口内的帖子按从新到旧返回。它边跑边把每条新帖子写入输出文件,并按 tweet_id 去重。如果中途停止,用同样的命令再运行一次即可:它会重做停下时所在的窗口,然后继续。
import json
import os
import sys
import time
from datetime import datetime, timezone
import requests
API = "https://api.twexapi.io/twitter/advanced_search/page"
HEADERS = {"Authorization": f"Bearer {os.environ['TWEXAPI_KEY']}"}
# python backfill.py "from:NASA" 2015-01-01 2015-04-01 nasa.jsonl [window minutes]
# Start and end are UTC (2015-01-01 or 2026-11-20T12:00), end excluded.
# Use short windows (10 to 60 minutes) for busy keywords; the default is one day.
QUERY, START, END, OUT = sys.argv[1:5]
WINDOW = int(sys.argv[5]) * 60 if len(sys.argv) > 5 else 24 * 3600
def unix(moment):
return int(datetime.fromisoformat(moment).replace(tzinfo=timezone.utc).timestamp())
def posted_at(post):
return int(datetime.strptime(post["created_at"], "%a %b %d %H:%M:%S %z %Y").timestamp())
def search(query, cursor):
body = {"searchTerms": [query], "sortBy": "Latest"}
if cursor:
body["next_cursor"] = cursor
for attempt in range(6):
try:
res = requests.post(API, headers=HEADERS, json=body, timeout=60)
if res.status_code != 429 and res.status_code < 500:
res.raise_for_status()
page = res.json()
return [post for post in page.get("data") or [] if post], page.get("next_cursor")
except (requests.ConnectionError, requests.Timeout):
pass
time.sleep(2**attempt) # rate limited, server error or network drop: wait and retry
raise RuntimeError("search kept failing")
first, last = unix(START), unix(END)
# Resume: windows before the newest one with saved posts in this range are done; redo that one.
seen, resume = set(), first
if os.path.exists(OUT):
for line in open(OUT):
post = json.loads(line)
seen.add(post["tweet_id"])
if first <= posted_at(post) < last:
resume = max(resume, first + (posted_at(post) - first) // WINDOW * WINDOW)
with open(OUT, "a") as out:
for since in range(resume, last, WINDOW):
until = min(since + WINDOW, last)
query = f"{QUERY} since_time:{since} until_time:{until}"
cursor, saved = None, 0
while True:
posts, next_cursor = search(query, cursor)
for pause in (2, 4, 8): # an empty page is often a hiccup: ask for the same page again
if posts:
break
time.sleep(pause)
posts, next_cursor = search(query, cursor)
for post in posts:
if post["tweet_id"] not in seen:
seen.add(post["tweet_id"])
out.write(json.dumps(post, ensure_ascii=False) + "\n")
saved += 1
if not posts or not next_cursor:
break
cursor = next_cursor
out.flush()
print(f"{datetime.fromtimestamp(since, timezone.utc):%Y-%m-%d %H:%M}: {saved} new, {len(seen)} saved", flush=True)
QUERY 可以使用任何搜索运算符,例如 from:NASA、"climate change" lang:en 或 #bitcoin -filter:replies。不要再写日期运算符,脚本会自动加上时间边界。
5. 运行
python backfill.py "from:NASA" 2015-01-01 2015-04-01 nasa.jsonl
2015-01-01 00:00: 10 new, 10 saved
2015-01-02 00:00: 8 new, 18 saved
...
2015-03-31 00:00: 10 new, 1483 saved
这次运行用了 33 分钟,其中大部分是 90 个窗口结尾各约 14 秒的重试等待。等待不占用速率限制,所以按月并行运行可以缩短总时间(见下文)。
热门关键词请再传入以分钟为单位的窗口长度:
python backfill.py "bitcoin" 2026-11-21T12:00 2026-11-21T12:10 bitcoin.jsonl 10
2026-11-21 12:00: 341 new, 341 saved
这个窗口用了 67 秒。
检查导出结果有没有缺口
按天统计帖子数,找出比相邻日期明显偏少或为零的日子:
import collections
import json
from datetime import datetime
days = collections.Counter(
datetime.strptime(json.loads(line)["created_at"], "%a %b %d %H:%M:%S %z %Y").date()
for line in open("nasa.jsonl")
)
for day, count in sorted(days.items()):
print(day, count)
要重新检查某一天,只需对那一天运行脚本并写入同一个文件。已有的帖子会被跳过,只会补上缺失的:
python backfill.py "from:NASA" 2015-02-18 2015-02-19 nasa.jsonl
单次运行仍可能漏掉少量帖子。from:NASA 2015 年 1 月到 3 月的两次运行分别漏掉了 9 条和 20 条,合并后得到全部 1,492 条。我们还对 bitcoin 2026 年 11 月 21 日 12 到 12 跑了两遍,一遍用一个 10 分钟窗口,一遍用 1 分钟窗口,分别找到 341 条和 346 条,合起来 354 条。如果数据集必须完整,请把同一范围再跑一遍写入另一个文件,然后按 tweet_id 合并:
import json
posts = {}
for name in ("pass1.jsonl", "pass2.jsonl"):
for line in open(name):
post = json.loads(line)
posts[post["tweet_id"]] = post
with open("merged.jsonl", "w") as out:
for post in posts.values():
out.write(json.dumps(post, ensure_ascii=False) + "\n")
热门关键词约一周后会变稀疏
对于热门关键词,帖子发布约一周后,搜索返回的数量会大幅减少。在我们的测试中,from:NASA 这类账号搜索不受影响。以下是 2026 年 11 月 28 日搜索 bitcoin 的结果(时间均为 UTC):
| 搜索范围 | 翻页方式 | 帖子发布了多久 | 返回帖子数 |
|---|---|---|---|
| 11 月 20 日 12 到 13,00 搜索 | max_id: |
7.5 天 | 1,774 |
| 同一小时,14 搜索 | max_id: |
8.1 天 | 42,第二次运行 39 |
| 11 月 20 日 12 到 12 | 1 分钟窗口 | 8.1 天 | 117 |
| 11 月 21 日 12 到 12 | 1 分钟窗口 | 7.1 天 | 346 |
| 2021 年 11 月 20 日 12 到 12 | 1 分钟窗口 | 5 年 | 110 |
如果你需要某个热门关键词的全部帖子,请从现在开始采集并保持更新(见下文),或者在帖子发布满一周之前完成回填。回填更早的范围只能拿到其中一部分。
加快大规模回填
在热门关键词上,单个进程每小时约保存 18,000 条帖子,每次请求约 2 秒。要更快,可以把范围按月拆开,每月运行一个进程,各自写入自己的文件。总请求速率不要超过你的套餐的每秒请求数:免费 Starter 0.2、Mini 1、Lite 3、Basic 5、Pro 10、Business 20。脚本遇到限流时会等待并重试。
python backfill.py "from:NASA" 2015-01-01 2015-02-01 nasa-01.jsonl &
python backfill.py "from:NASA" 2015-02-01 2015-03-01 nasa-02.jsonl &
python backfill.py "from:NASA" 2015-03-01 2015-04-01 nasa-03.jsonl &
wait
cat nasa-0*.jsonl > nasa.jsonl
保持数据集最新
TwexAPI 没有 firehose 或流式接口。回填完成后,每隔几分钟用同一个查询运行一次,把 since_id: 设为已保存的最新 tweet_id,然后追加新帖子。每条新帖子 5 Credits,没有找到新帖子的检查花 5 Credits。
历史帖子包含哪些内容
- 每条帖子约 50 个字段:正文、时间、语言、媒体、链接、话题标签,以及回复和引用的 ID。
- 点赞、转发、回复、引用和浏览量是你获取时的数值,而不是发布时的数值。较早的帖子浏览量返回 0:NASA 2015 年 1 月 1 日的 10 条帖子全部如此。
- 作者资料是现在的资料。
- 不包含已删除的帖子,也不包含受保护或被封禁账号的帖子。
费用
每返回一条帖子花 5 Credits,约每 1,000 条 $0.05,每 100 万条 $50。空页花 5 Credits,失败的请求不收费。上面的 NASA 回填约花了 9,300 Credits,约 $0.09。准确单价见价格说明,与官方 X API 的价格对比见 Twitter 历史数据(英文)。
下一步
- 用 Python 抓取 Twitter:搜索、粉丝和 CSV 导出。
- 速率限制:套餐限制和长任务的退避方式。
- 错误处理:遇到
429和5xx时如何重试和退避。 - 只采集公开数据,并遵守隐私法规和 X 的条款。