从列表中删除不再存在的twitter用户(使用Tweepy)

2024-07-05 14:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我一直在尝试从一个列表中删除不存在的twitter用户。我想这么做的原因是,我运行代码的时候,一些twitter用户已经不存在了,我得到了这个错误

kages/tweepy-3.6.0-py3.6.egg/tweepy/binder.py", line 234, in execute
tweepy.error.TweepError: [{'code': 34, 'message': 'Sorry, that page does not exist.'}]

我无法完成我的数据收集,因为这个错误一直在阻止代码表单的运行,所以我一直在手动地逐一查看我的列表,找到twitter上不存在的twitter帐户,这是非常低效的。 所以我一直在尝试使用try-except块来覆盖这段代码,比如删除不再存在的用户名并继续运行我的程序,但是我尝试的一切都不起作用。这是我的尝试,除了block without tweepy(只是普通代码)之外,它是有效的。在

^{pr2}$

现在我试着在我的twitter列表中实现这一点

^{3}$

但它不起作用。它只需通过pro-tu-trump列表删除列表中的每个用户名,而不管tweeter帐户是否仍然存在。 有人能帮我实现我真正希望我的代码能做什么吗?在


Tags: 代码用户inpy列表egg错误line
1条回答
网友
1楼 · 发布于 2024-07-05 14:32:33

问题是由您调用api.friends_ids引起的,它引发了一个超过速率限制的错误。这又会触发每个循环中的except代码块,而不管{}是否正确。如果没有速率限制错误,代码将按原样工作。我用api.get_user(id=screen_name)代替了这个调用来测试。您可以在except内包含一个if-else块,以便仅在错误正确时删除用户。我还优化了代码,将for循环放在try-except块之外。在

pro_trump=['TruthSerum888','karlyherron', 'R41nB14ck', 'RedApplePol', 'MKhaoS_86']
for screen_name in pro_trump:
    try:
        user_followers=api.friends_ids(id=screen_name)# this returns the interger value of the user id a sepcifc user is following

    except tweepy.error.TweepError as t:
        if t.message[0]['code'] == 50: # The code corresponding to the user not found error
            print("screen_name that failed=",  screen_name)
            pro_trump.remove(screen_name)
            print(pro_trump)
        elif t.message[0]['code'] == 88: # The code for the rate limit error
            time.sleep(15*60) # Sleep for 15 minutes
    else:# if no error
        print(pro_trump)

这样,在末尾也不需要continues,因为它已经到达了它正在执行的代码块的末尾,并且无论如何都会继续循环。在

相关问题 更多 >