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



嗨,我一直在尝试从列表中删除不存在的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.'}]

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

l=["b",23,"c",6,5]
print(l)
for i in range(0,10):
try:
for a in l:
print("a=",int(a))
except ValueError:
l.remove(a)
print(l)
continue
else:
print(l)
continue

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

pro_trump=['TruthSerum888','karlyherron', 'R41nB14ck', 'RedApplePol', 'MKhaoS_86']
for i in range(0,3):
try:
for screen_name in pro_trump:
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:
print("screen_name that failed=",  screen_name)
pro_trump.remove(screen_name)
print(pro_trump)
continue
else:# if no error
print(pro_trump)
continue

但它不起作用。它只是遍历protrump列表,通过列表删除每个用户名,而不管推特用户帐户是否仍然存在。有人能帮我实现我真正希望我的代码能做的事情吗?

问题是由您对api.friends_ids的调用引起的,该调用引发了超出速率限制的错误。这反过来触发每个循环中的except代码块,而不管screen-name是否正确。在没有速率限制错误的情况下,代码可以正常工作。我用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)

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

最新更新