如何使用tweepy获得最新的用户状态

Joh*_*ohn 4 python twitter tweepy

我试图使用tweepy来获取最新的用户状态

我的代码是

api = tweepy.API(auth)
for status in tweepy.Cursor(api.user_timeline).items():
    lastid = status.id
    laststatus = api.get_status(lastid).text
    break
Run Code Online (Sandbox Code Playgroud)

有用.但我必须使用循环.有没有更好的方法?

Mar*_*ers 5

.items()返回一个迭代器,所以你可以简单地调用next()来获取第一个项目:

status = next(tweepy.Cursor(api.user_timeline).items())
Run Code Online (Sandbox Code Playgroud)

如果根本没有任何项目,这可能会引发StopIteration异常.您可以添加默认值next()以防止:

status = next(tweepy.Cursor(api.user_timeline).items(), None)
Run Code Online (Sandbox Code Playgroud)