【问题标题】:Is there a way to fetch tweets from a specific user during a specific time frame using tweepy?有没有办法使用 tweepy 在特定时间范围内从特定用户那里获取推文?
【发布时间】:2021-04-17 23:58:45
【问题描述】:

我正在尝试从两个日期之间的特定帐户获取有关推文的信息(喜欢的数量、cmets 等)。我可以访问 Twitter API 和安装的 tweepy,但我无法弄清楚如何做到这一点。我的身份验证方法是 OAuth 2.0 Bearer Token。任何帮助表示赞赏!

【问题讨论】:

    标签: twitter tweepy twitterapi-python


    【解决方案1】:

    您可以通过查看推文对象下的created_at 属性来检查推文的创建时间。但是,要在特定时间范围内从特定用户那里获取所有推文,您必须首先获取该帐户下的所有推文。另外,值得一提的是,Twitter 的 API 仅支持最多 3200 条用户最新的推文。

    要获取所有推文,您可以这样做

    # Get 200 tweets every time and add it onto the list (200 max tweets per request). Keep looping until there's no more to fetch.
    username = ""
    tweets = []
    fetchedTweets = twitterAPI.user_timeline(screen_name = username, count = 200)
    tweets.extend(fetchedTweets)
    lastTweetInList = tweets[-1].id - 1
    
    while (len(fetchedTweets) > 0):
            fetchedTweets = twitterAPI.user_timeline(screen_name = username, count = 200, max_id = lastTweetInList)
            tweets.extend(fetchedTweets)
            lastTweetInList = tweets[-1].id - 1
            print(f"Catched {len(tweets)} tweets so far.")
    

    然后,您必须过滤掉属于您特定时间范围内的所有推文(您必须导入日期时间):

    start = datetime.datetime(2020, 1, 1, 0, 0, 0)
    end = datetime.datetime(2021, 1, 1, 0, 0, 0)
    specificTweets = []
    for tweet in tweets:
        if (tweet.created_at > start) and (tweet.created_at < end):
            specificTweets.append(tweet)
    

    您现在可以在specificTweets 中查看属于您的时间范围内的所有推文。

    【讨论】:

    • 非常感谢!这行得通!一个后续问题:有没有办法获得每个状态对象的评论计数?我可以得到 favorite_count 和 retweet_count,但不能得到 tweet 上的 cmets 数。
    • 另外,转推的喜爱计数为零,有没有什么好办法也​​能得到这个数字?
    • 似乎每个状态对象的评论计数无法使用 API 获得,除非您拥有 Premium/Enterprise 分层 API (read the docs here under "reply_count")。没有直接的方法可以访问回复计数,但我发现另一篇文章展示了如何从另一个属性访问它:[stackoverflow.com/questions/2693553/…。我不知道你所说的最喜欢的转发次数是什么意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 2017-12-12
    • 2015-10-08
    • 2011-03-30
    • 1970-01-01
    相关资源
    最近更新 更多