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

大学情感分析项目求助:如何用Twitter API从推文ID提取文本

如何通过Twitter API利用推文ID提取完整推文文本

核心方案:使用Twitter API v2的/tweets端点

Twitter API v2是当前官方推荐的接口,支持批量查询推文,具体步骤如下:

  1. 确认API权限
    确保你的开发者账号已申请tweet.read权限,并且获取到Bearer Token(可在开发者平台的项目密钥页面找到)。

  2. 读取本地推文ID文件
    从.txt文件中读取所有推文ID,注意将ID转为字符串(避免长数字溢出问题):

    with open("tweet_ids.txt", "r") as f:
        tweet_ids = [line.strip() for line in f if line.strip()]
    
  3. 批量调用API提取推文
    Twitter API允许一次查询最多100个推文ID,需分批处理。以下是Python示例(依赖requests库,可通过pip install requests安装):

    import requests
    
    BEARER_TOKEN = "替换为你的Bearer Token"
    batch_size = 100
    all_tweets = []
    
    # 分批处理ID列表
    for i in range(0, len(tweet_ids), batch_size):
        current_batch = tweet_ids[i:i+batch_size]
        ids_param = ",".join(current_batch)
        api_url = f"https://api.twitter.com/2/tweets?ids={ids_param}&tweet.fields=text,created_at"
    
        headers = {"Authorization": f"Bearer {BEARER_TOKEN}"}
        response = requests.get(api_url, headers=headers)
    
        if response.status_code == 200:
            response_data = response.json()
            # 收集成功获取的推文
            all_tweets.extend(response_data.get("data", []))
            # 处理无法获取的推文(如已删除、私有)
            if "errors" in response_data:
                for err in response_data["errors"]:
                    print(f"ID {err['value']} 无法获取: {err['detail']}")
        else:
            print(f"请求失败,状态码 {response.status_code}: {response.text}")
    
  4. 保存提取结果
    将获取到的推文ID和文本保存到本地,方便后续清洗与分析:

    with open("extracted_tweets.txt", "w", encoding="utf-8") as f:
        for tweet in all_tweets:
            f.write(f"{tweet['id']}\t{tweet['text']}\n")
    

关键注意事项

  • 速率限制:API v2的/tweets端点限制为900次请求/15分钟,按每批100个ID计算,每15分钟最多可查询90000条推文,按需调整批次间隔。
  • 缺失推文处理:部分推文可能因删除、账号封禁或隐私设置无法获取,这些会在响应的errors字段中返回,建议记录这些ID以便后续排查。
  • 权限扩展:如果需要提取敏感内容(如成人内容、政治敏感内容),需在开发者平台额外申请对应权限。

内容的提问来源于stack exchange,提问作者Megi Çeka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 11:10:53