如何解决tweepy 没有给我最后一条推文
我正在尝试使用 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_replys')
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.
这是他的最后一个回复,所以这是有效的。
我无法从他的时间轴中获取最后一条实际推文
解决方法
正如评论中提到的Iain Shelvington,exclude_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)
注意:在获取 last_tweet
之前应该检查 None
不是 full_text
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。