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

如何在Twitter API中调用多个user_name获取用户数据?

问题分析与修复

你的代码存在两个核心问题:

  • 重复定义get_all_tweets函数,第二个函数会直接覆盖第一个,导致后续调用的是有bug的版本
  • 第二个函数的循环里犯了低级错误:遍历tweets1.data时用的是tweet1变量,但append字典时却引用了未定义的tweet,直接引发报错,自然生成不了userTweets1列表

完全没必要复制函数,复用原本正常的get_all_tweets即可,直接遍历多个用户名就能批量获取数据。

修复后的完整代码:

import tweepy
import pandas as pd
import webbrowser
import time

def get_all_tweets(user_name):
    bearer_token ='XXX'
    client = tweepy.Client(bearer_token=bearer_token)

    user = client.get_user(username = user_name)
    user_id = user.data.id
    userTweets = []
    count = 0
    limit = 3000
    pagination_token = None
    start_time = '2023-03-01T00:00:00Z' # YYYY-MM-DDTHH:mm:ssZ
    end_time   = '2023-03-02T00:00:00Z' # YYYY-MM-DDTHH:mm:ssZ
    while count < limit:
        tweets = client.get_users_tweets(
            id = user_id,
            exclude = ['retweets','replies'],
            tweet_fields = ['created_at','public_metrics'],
            pagination_token = pagination_token,
            start_time = start_time,
            end_time = end_time,
            max_results = 100)
        if 'next_token' in tweets.meta.keys():
            if (tweets.meta['next_token']) is not None:
                pagination_token = tweets.meta['next_token']
            else:
                pagination_token = None
        else:
            pagination_token = None
        if tweets.data is not None:
            for tweet in tweets.data:
                count += 1
                userTweets.append({
                "id": tweet.id,
                "text": tweet.text,  # 修正原代码笔误:"test"应为"text"
                "date": tweet.created_at,
                "public":tweet.public_metrics
                })
        if pagination_token is None:
            break
    return userTweets, count

# 定义需要获取数据的用户名列表
target_users = ['Weltwoche', 'Blick']

# 批量获取并存储所有用户数据
all_user_data = {}
for username in target_users:
    tweets, tweet_count = get_all_tweets(username)
    all_user_data[username] = {
        "tweets": tweets,
        "count": tweet_count
    }

# 输出所有结果
for username, data in all_user_data.items():
    print(f"用户 {username} 的推文数量:{data['count']}")
    for tweet in data['tweets']:
        print(tweet)

额外说明:

  • 修正了原函数里的字段名笔误,避免后续数据处理出错
  • 用字典统一存储所有用户的数据,结构更清晰,后续导出或分析更方便
  • 复用同一个函数,减少重复代码,降低出错概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:47:49