Twitter 上的错误条件 "user not found" python

error condition "user not found" on twitter with python

我想通过他们的用户名在 Twitter 中找到用户身份,数据已经保存在我的数据库中

我做了这样的条件

#get data from database
cur.execute("SELECT user FROM `rt6`")
row = cur.fetchall()

for text in row:
    #Get Identity of BMKG in Twitter
    user = api.get_user(text)
    try:
        print ("Name:", user.name)
        print ("Name:", user.screen_name)
        print ("Number of tweets: " + str(user.statuses_count))
        print ("followers_count: " + str(user.followers_count))
        print ("Account location: ", user.location)
        print ("Account created at: ", user.created_at)
        print ("Account geo enabled: ", user.geo_enabled)
    except ValueError:
        print("user not found")

我的目标是当用户在我的数据库中找不到一个用户名时,直接跳到数据库中的下一行。

我遇到了这样的错误,有人能解决我的问题吗?

异常是从 api.get_user(...) 调用中抛出的。但是您没有处理该行抛出的异常。您只处理它下面的任何 print 语句抛出的异常。让我通过在您的代码中添加一些注释来澄清这一点:

for text in row:
    #Get Identity of BMKG in Twitter
    user = api.get_user(text) ### Exception thrown on this line

    try:   ### Exception handling starts here
        print ("Name:", user.name)
        print ("Name:", user.screen_name)
        print ("Number of tweets: " + str(user.statuses_count))
        print ("followers_count: " + str(user.followers_count))
        print ("Account location: ", user.location)
        print ("Account created at: ", user.created_at)
        print ("Account geo enabled: ", user.geo_enabled)
    except ValueError:
        print("user not found")

尝试将调用移至 try 块内的 api.get_user。我还按照评论中的建议调整了被捕获的异常:

for text in row:
    try:
        #Get Identity of BMKG in Twitter
        user = api.get_user(text)
        print ("Name:", user.name)
        print ("Name:", user.screen_name)
        print ("Number of tweets: " + str(user.statuses_count))
        print ("followers_count: " + str(user.followers_count))
        print ("Account location: ", user.location)
        print ("Account created at: ", user.created_at)
        print ("Account geo enabled: ", user.geo_enabled)
    except tweepy.error.TweepError:
        print("user not found")