【问题标题】:tweepy is not giving me the last tweettweepy 没有给我最后一条推文
【发布时间】:2023-04-08 20:37:02
【问题描述】:

我正在尝试在 python 中使用 tweepy 获取来自 Twitter 帐户的最后一条推文。

我知道有一些类似的答案,例如这个Get the last tweet with tweepy

但是我遇到的问题是我没有从个人时间轴上获得最后一条推文,而是第二条推文。

我在 while 循环中使用此代码:

tweetL = api.user_timeline(screen_name='elonmusk', tweet_mode="extended", exclude_replies, count=1)
    print(tweetL[0].full_text)

如果我运行这个(在撰写本文时),我会从 Elon 收到这条推文:

What a beautiful day in LA

但是看看他的时间线,他的最后一条推文是这样的:

Warm, sunny day & snowy mountains

那么为什么我没有收到最后一条推文? 奇怪的是,昨晚运行这个脚本确实打印出了他的最后一条推文。 现在运行它,我得到了相同的推文,昨天打印出来的最后一条推文

如果我像这样运行上面的代码(没有'exclude_replies')

tweetL = api.user_timeline(screen_name='elonmusk', tweet_mode="extended")
    print(tweetL[0].full_text)

我得到了他的最后一条推文

@ErcXspace @smvllstvrs T/W will be ~1.5, so it will accelerate unusually fast. High T/W is important for reusable vehicles to make more efficient use of propellant, the primary cost. For expendable rockets, throwing away stages is the primary cost, so optimization is low T/W.

这是他最后的回复,所以这行得通。

我只是无法从他的时间线中获取最后一条实际推文

【问题讨论】:

  • 这条推文(“温暖、阳光明媚的日子和雪山”)是一个回复,您将 exclude_replies 传递给您的 API 调用
  • 让我更新问题
  • @joeblow,正确,是他的newest reply

标签: python twitter tweepy


【解决方案1】:

正如cmets中提到的Iain Shelvingtonexclude_replies也会忽略对自己的回复。

我认为没有直接的方法可以在用户的​​时间线中获取用户的最后一条推文。您可以创建一个函数,从检索到的推文中获取第一个:

a) 不是回复,即in_reply_to_screen_name = None

b) 或回复自己,即in_reply_to_screen_name = screen_name

这可能看起来像:

def get_last_timeline_tweet(screen_name: str, tweets: list):
    for tw in tweets:
        if (tw.in_reply_to_screen_name is None or
                tw.in_reply_to_screen_name == screen_name):
            return tw
    return None

然后,运行:

last_timeline_tweet = get_last_timeline_tweet('elonmusk', tweetL).full_text
print(last_timeline_tweet)

你得到:

Warm, sunny day & snowy mountains [url to the photo]

这也可以通过以下方式在单行中完成:

screen_name = 'elonmusk'

last_tweet = next((tw for tw in tweetL if tw.in_reply_to_screen_name is None
                   or tw.in_reply_to_screen_name == screen_name), None)

print(last_tweet.full_text)

注意:在得到full_text之前,应该检查last_tweet不是None

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 2022-01-02
    • 2022-06-11
    • 2021-03-28
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    相关资源
    最近更新 更多