Python 按用户名拉 X 时间线:先解析 handle,再翻 next_cursor

发布于 2026年10月12日 · 更新于2026年10月16日

很多人手里只有一份公开用户名名单,第一反应是拿这个名字去搜:query=NASA,再加 search_type=Latest,把返回的帖全部算成 NASA 自己发的。搜索不是这个账号的时间线。 search 认的是文本。文档里用 NASA 做过查询,命中里出现过小写 nasa、不相干作者、别的语言。品牌词对上了,不等于作者就是这个账号。user-timeline 才按账号取近期帖。它的 next_cursor 不是搜索那本账;表格里的 handle 在 user-info 认过之前,也还不是用户 ID。

下面这段 Python:先解析 handle,碰到 notfound 就停,再在同一账号上原样回传 next_cursor,推文 id 全程当字符串。打开本页或复制代码不会发请求;换成真实密钥并执行后才会调用、才会扣额度。

X(Twitter)公开数据 API 是独立的只读 GET,不是官方接口,也不保证完整历史或实时流。公开计数是采集当下的快照。

登录后从控制台复制你有权使用的 Key,放到服务端环境变量 OPENDATA_API_KEY。文中的 YOUR_API_KEY 只是占位。Key 走查询串,日志、工单、截图和前端都不要带完整 URL。不需要 X 密码或 Cookie。

搜索不是这个账号的时间线

搜索必填 query。已验证的模式是 search_type=Latest,别的取值这里不承诺。翻页只认同一次查询、同一种模式带回的 next_cursor。命中里有 tweet_id、text、screen_name、user_info。先核 user_info.rest_id,再决定算不算目标账号。品牌监测走搜索;要「这个账号自己发的帖」,走时间线。

把搜索游标塞进 user-timeline,等于两本账对冲。网关不会把关键词页翻译成账号页。跳过解析、把 NASA 当成数字 ID,等于从没确认账号在不在,也从没拿到字符串 rest_id。用户名会改,rest_id 相对稳。

users-media 仍按 screenname 取带媒体的账号帖,不是关键词结果。followers、following 翻的是人,游标另算。tweet-info 只认一条字符串 id。任务是「这个账号近期发了什么」时,它们都替不了 user-timeline。

搜索导出请留下 query 和采集时间,相关性自己过滤。不要因为查询词碰巧等于 handle,就把文件改名为时间线。

先解析 handle,再翻 next_cursor

user-info 必填不带 @ 的 screenname。文档里的公开例子是 NASA。可选 rest_id 会覆盖按用户名选取,但 schema 仍要 handle,不能只丢 ID。命中时 status=active,读 rest_id,先转成字符串再进时间线。

响应有两层。HTTP 4xx/5xx 是传输、鉴权或额度,请求没跑成。HTTP 200 不等于成功:信封是 {code, message, data},业务成功看 code=200。然后再读 data。网关成功但 status=notfound,是未找到,不是空时间线。排错只留脱敏后的 code 和 message;异常栈里的完整 URL 会把 Key 带出去。

时间线第一页:screenname,若要钉死账号就带上解析出的 rest_id。不要传 cursor,也不要用空字符串占坑。已观察到的载荷是 status=ok、timeline、user、next_cursor、prev_cursor。把 next_cursor 原样回传为 cursor,账号中途不要换。游标缺失、空串、纯空白或重复就停。页长以实际 timeline 为准,那是观察值,不是合同。停手不等于拿完全部历史。

安装 requests,密钥只从环境变量读。下面的页预算 max_pages=3 是客户端自己设的,不是服务端限额。网络、HTTP、网关或业务异常都停,不自动重试,也不打印带密钥的 URL。

import os
import time

import requests

BASE = "https://api.opendata-api.com/api/project/twitter"
KEY = os.environ["OPENDATA_API_KEY"].strip()
if not KEY:
    raise RuntimeError("Missing API key")


def read(operation, **params):
    try:
        response = requests.get(
            f"{BASE}/{operation}", params={"key": KEY, **params}, timeout=30
        )
    except requests.RequestException:
        raise RuntimeError("Network request failed") from None
    if not 200 <= response.status_code < 300:
        raise RuntimeError(f"HTTP {response.status_code}; collection stopped")
    try:
        envelope = response.json()
    except ValueError:
        raise RuntimeError("Invalid JSON response") from None
    if not isinstance(envelope, dict) or str(envelope.get("code")) != "200":
        raise RuntimeError("Platform request failed")
    data = envelope.get("data")
    if not isinstance(data, dict):
        raise RuntimeError("Unexpected business response")
    return data


def iter_tweets(screenname, max_pages=3):
    profile = read("user-info", screenname=screenname)
    if profile.get("status") == "notfound":
        return
    if profile.get("status") != "active" or not profile.get("rest_id"):
        raise RuntimeError("Profile could not be resolved")
    if profile.get("protected") is True:
        return  # Private content is out of scope
    target_id = str(profile["rest_id"])
    cursor = None
    seen_ids, seen_cursors = set(), set()
    for _ in range(max_pages):
        params = {"screenname": screenname, "rest_id": target_id}
        if cursor is not None:
            params["cursor"] = cursor  # Pass the opaque cursor unchanged
        data = read("user-timeline", **params)
        if data.get("status") != "ok" or not isinstance(data.get("timeline"), list):
            raise RuntimeError("Timeline status or structure is unexpected")
        for tweet in data["timeline"]:
            if not isinstance(tweet, dict):
                raise RuntimeError("Unexpected post record")
            tweet_id = tweet.get("tweet_id")
            author = tweet.get("author")
            if tweet_id is None or not isinstance(author, dict):
                continue
            tweet_id = str(tweet_id)
            if not tweet_id or tweet_id in seen_ids:
                continue
            if str(author.get("rest_id")) != target_id:
                continue
            if tweet.get("retweeted") or tweet.get("retweeted_tweet"):
                continue
            seen_ids.add(tweet_id)
            yield tweet
        next_cursor = data.get("next_cursor")
        if next_cursor is None or next_cursor == "":
            return
        if not isinstance(next_cursor, str):
            raise RuntimeError("Unexpected cursor type")
        if next_cursor in seen_cursors:
            return
        seen_cursors.add(next_cursor)
        cursor = next_cursor
        time.sleep(1)  # Deliberate pacing, not a documented rate limit


if __name__ == "__main__":
    for tweet in iter_tweets("NASA"):
        print(str(tweet["tweet_id"]), tweet.get("created_at"), tweet.get("text"))

后面几页带了 rest_id,也仍要留 screenname。只按用户名选账号时,去掉 rest_id,照样核返回的作者 ID。游标当不透明字节:不拆、不自增,也不拿搜索、媒体、粉丝列表的游标来顶。相邻页可能重叠,所以字符串 tweet_id 去重和翻页写在同一段循环里。time.sleep(1) 是本地节奏,不是文档里的限流合同。

临时故障可以做有上限的退避;notfound 不要重试。别为了「感觉还没翻完」死循环——可用历史会变,每一页都耗额度。用量以定价为准。

推文 id 当字符串留

X 的 id 超出 JavaScript 安全整数。解析成 Number 再转回字符串,缺的位补不回来。Python、JSONL、数据库列都当文本。上面的脚本在放进集合前先 str(...),就是为了这件事。

一次运行里用字符串 id 去重。定时任务要把 (target_id, tweet_id) 落到库;内存集合进程一退就没了。示例生成器不写文件,跨次运行仍要靠你自己的唯一键。

时间线里点赞字段是 favorites,tweet-info 里是 likes。views 可能是数字字符串。计数缺失就留空,补零等于捏造活跃。每条记下采集时间:计数会变,快照时刻是记录的一部分。转发可能带 retweeted、retweeted_tweet,作者也可能是空。作者对不上或带转发标记的,示例直接跳过,所以产出条数可以少于接口返回条数。要研究扩散,把转发上下文另存,不要算进目标账号原创。

需要补一条详情——展示文案、媒体、更新后的互动——在循环之后用已采集的字符串 id 调 tweet-info,不要在页预算里逐条打。先看该操作自己的业务状态,再读作者、媒体和 likes。帖子不可用时的形态这里尚未验证。

notfound 不是空时间线

未找到的 handle,已验证形态是 status=notfound,身份和计数都是 null。这不是「活跃账号、零条推文」。不要把 null 写成零粉丝,不要接着打时间线,也不要把同一输入当抖动重试。改用户名,或把这行标成本次不可用。

时间线 status 不是 ok,或 timeline 不是列表,属于结构异常:停解析,别改写成空数组当成功。active 资料上 timeline 为空,可能只是这段窗口没帖,仍然不是 notfound。protected 为真就不要排队翻页——公开采集拿不到私密内容。

导出时写下:送进去的 handle、解析出的 rest_id、采集窗口、页预算、停手原因。不要把文件标成完整档案。公开链接不代表转载许可。

脚本能跑之后仍常见的错:搜 handle 把命中当时间线;把搜索的 next_cursor 塞进 user-timeline;没走 user-info 就把用户名当用户 ID;传 page=2 或自增游标;有了 rest_id 就丢掉必填 screenname;把 tweet_id 存成数字;把 notfound 当成零活跃;HTTP 200 当命中;对未找到原地重试;循环里逐条打 tweet-info;把带 Key 的完整 URL 打进日志。

参考 user-timeline、user-info、search、tweet-info。单次调用费用见定价。