使用Mastodon Python API获取关注与粉丝列表结果相同?
Mastodon Python API获取关注/粉丝列表数量异常问题
问题描述
尝试通过Mastodon Python API获取自己的关注列表和粉丝列表,但调用account_followers与account_following接口返回的结果数量一致。代码如下:
myid = mastodon.account_verify_credentials()["id"] followed_by = mastodon.account_followers(myid) #Fetch users the given user is followed by. following = mastodon.account_following(myid) # Fetch users the given user is following. binoff = [] print ("followed_by={}, following={}, binoff={}".format(len(followed_by),len(following),len(binoff)))
运行结果:
followed_by=40, following=40, binoff=0
followed_by=40, following=40, binoff=40
问题原因与解决方法
核心原因
Mastodon的account_followers和account_following接口默认只返回第一页的40条数据,这是API的分页限制。你当前的代码仅获取了第一页内容,所以如果粉丝/关注的第一页数据量都是40,就会显示数量一致,但这并非完整的列表数据。
解决方法
需要循环获取所有分页数据,利用Mastodon Python库提供的fetch_next方法迭代获取下一页内容,直到没有更多数据为止。同时可以正确计算双向关注的数量,修改后的代码如下:
myid = mastodon.account_verify_credentials()["id"] # 获取完整粉丝列表 followed_by = [] next_page = mastodon.account_followers(myid) while next_page: followed_by.extend(next_page) next_page = mastodon.fetch_next(next_page) # 获取完整关注列表 following = [] next_page = mastodon.account_following(myid) while next_page: following.extend(next_page) next_page = mastodon.fetch_next(next_page) # 计算双向关注(互关)的用户数量 followed_ids = {user["id"] for user in followed_by} binoff = [user for user in following if user["id"] in followed_ids] print(f"followed_by={len(followed_by)}, following={len(following)}, binoff={len(binoff)}")
补充说明
- 使用集合存储粉丝ID可以提升互关判断的效率,避免多次列表遍历。
- 若你的粉丝或关注总数确实为40,那返回数量一致是正常情况;但如果总数超过40,只有获取所有分页数据才能得到真实数量。
内容的提问来源于stack exchange,提问作者Rick Dearman
相关产品推荐
相关产品推荐

