使用Twython获取用户Twitter关注时遇到429错误
我在这个网站上看到了一些关于这个问题的讨论,但我还是搞不清楚自己哪里出错了。
这段代码本来是用来获取关注者列表的,但无论我怎么尝试,都会从Twitter的API那里收到一个429错误:
def get_follow_list():
next_cursor = -1
while next_cursor != 0:
response = twitter.get_followers_list(screen_name=current_user, cursor=next_cursor)
following = response['users']
follow_list = [following]
time.sleep(1)
cursor = response['next_cursor']
return (follow_list)
我该怎么解决这个问题呢?
补充一下:别人给的代码很好,但在我尝试打印它的值时出现了这个错误:“UnicodeEncodeError: 'UCS-2' 编码无法编码位置205571-205571的字符:非BMP字符在Tk中不支持”。这又导致了之前提到的调用GUI类的问题。我不太确定怎么把列表的编码改成我的应用程序中的列表框可以处理的格式。
1 个回答
1
根据Twitter的错误代码和响应,当你看到一个429
的响应代码时,这意味着请求过多
。这说明问题不在于你的代码写得是否正确,而是你对Twitter API的调用次数太多了。你可以查看REST API的速率限制文档,了解如何跟踪你可以进行多少次调用(特别是使用X-Rate-Limit-Remaining
和其他HTTP头信息),以及每个REST接口的速率限制详情。
关于你提到的如何在获取前20个结果后进行分页的问题,可以查看使用游标。在这里,游标的条件应该是while cursor != 0:
,这样才能继续获取下一页的内容。同时,你需要确保不会对Twitter API进行过多的调用。
不过,我给你一个更好的解决方案,利用GET friends/ids
接口。这个接口可以让你一次性获取你关注的用户的ID,最多可以获取5000个(而不是20个),然后你可以在获取这些ID后,使用GET users/lookup
来获取更多信息。这样可以处理大量关注的用户,而不需要在每次调用之间暂停:
def get_follow_list():
users = []
users_ids = []
# Fetch the followings as a cursored collection (up to 5000 per call).
cursor = -1
while cursor != 0:
response = twitter.get_friends_ids(screen_name=current_user, cursor=cursor)
users_ids += response['ids']
cursor = response['next_cursor']
# Lookup the users by chunks of 100.
for i in range(0, len(users_ids), 100):
chunk = users_ids[i:i + 100]
users += twitter.lookup_user(user_id=chunk)
# Return the user objects.
return (users)