You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Twitter API v2仅返回10条结果,如何通过分页获取更多数据?

问题:Twitter API v2 仅返回10条结果,如何获取更多数据?是否与分页有关?

以下是我使用的Twitter API v2代码示例:

基础导入与Token设置

import requests
import os
import json

# To set your environment variables in your terminal run the following line:
# export 'BEARER_TOKEN'='<your_bearer_token>'
bearer_token = 'XYZ'

创建请求URL

def create_url():
    # Replace with user ID below
    user_id = 14699880
    return "https://api.twitter.com/2/users/{}/tweets".format(user_id)

请求参数设置

def get_params():
    # Tweet fields are adjustable.
    # Options include:
    # attachments, author_id, context_annotations,
    # conversation_id, created_at, entities, geo, id,
    # in_reply_to_user_id, lang, non_public_metrics, organic_metrics,
    # possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets,
    # source, text, and withheld
    return {"tweet.fields": "created_at"}

Bearer Token认证

def bearer_oauth(r):
    """
    Method required by bearer token authentication.
    """

    r.headers["Authorization"] = f"Bearer {bearer_token}"
    r.headers["User-Agent"] = "v2UserTweetsPython"
    return r

连接API端点

def connect_to_endpoint(url, params):
    response = requests.request("GET", url, auth=bearer_oauth, params=params)
    print(response.status_code)
    if response.status_code != 200:
        raise Exception(
            "Request returned an error: {} {}".format(
                response.status_code, response.text
            )
        )
    return response.json()

主函数调用

def main():
    url = create_url()
    params = get_params()
    json_response = connect_to_endpoint(url, params)
    print(json.dumps(json_response, indent=4, sort_keys=True))


if __name__ == "__main__":
    main()

问题:调用该代码仅返回10条结果,请问如何获取更多数据?这是否与pagination(分页)机制相关?


解答

是的,这完全和Twitter API v2的分页机制有关。默认情况下,/users/{user_id}/tweets端点单次请求最多返回10条推文,要获取更多数据,需要从两个方面调整代码:

1. 提高单页返回条数

修改get_params()函数,添加max_results参数,设置单次请求返回的最大推文数量(范围10-100,免费版上限为100):

def get_params():
    return {
        "tweet.fields": "created_at",
        "max_results": 100  # 单次请求最多返回100条
    }

2. 实现分页遍历所有可用结果

当用户的推文总数超过单页上限时,API会在返回结果的meta字段中提供next_token,你需要循环使用这个token来获取下一页数据。修改main函数来实现分页逻辑:

def main():
    url = create_url()
    params = get_params()
    all_tweets = []
    
    while True:
        json_response = connect_to_endpoint(url, params)
        # 将当前页的推文添加到总列表
        all_tweets.extend(json_response.get("data", []))
        
        # 检查是否存在下一页的token
        next_token = json_response.get("meta", {}).get("next_token")
        if not next_token:
            # 没有更多数据,退出循环
            break
        
        # 更新请求参数,加入分页token
        params["pagination_token"] = next_token
    
    print(f"共获取到 {len(all_tweets)} 条推文")
    print(json.dumps(all_tweets, indent=4, sort_keys=True))


if __name__ == "__main__":
    main()

关键说明

  • 免费版Twitter API最多只能获取用户最近的3200条推文,无法获取更早的内容
  • 请遵守API的速率限制,避免短时间内发起过多请求导致限流
  • 如果需要获取更早期的推文,需要申请更高权限的API访问权限

内容的提问来源于stack exchange,提问作者Picnic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:35:06