Tweepy 和 Python:如何列出所有关注者

dav*_*boc 0 python twitter tweepy

使用 Python 中的 tweepy,我正在寻找一种方法来列出一个帐户中的所有关注者,以及用户名和关注者数量。现在我可以通过这种方式获取所有 id 的列表:

ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="username").pages():
    ids.extend(page)
    time.sleep(1)
Run Code Online (Sandbox Code Playgroud)

但是有了这个 id 列表,我无法获得每个 id 的用户名和关注者数量,因为速率限制超过了......我如何完成这段代码?

谢谢你们!

Eff*_*gan 5

在 REST API 上,每 15 分钟允许进行180 次查询,我猜 Streaming API 也有类似的限制。你不想太接近这个限制,因为即使你没有严格达到它,你的应用程序最终也会被阻止。由于您的问题与速率限制有关,因此您应该在for循环中休眠。我会说 asleep(4)应该就足够了,但这主要是一个反复试验的问题,尝试更改该值并亲自查看。

就像是

sleeptime = 4
pages = tweepy.Cursor(api.followers, screen_name="username").pages()


while True:
    try:
        page = next(pages)
        time.sleep(sleeptime)
    except tweepy.TweepError: #taking extra care of the "rate limit exceeded"
        time.sleep(60*15) 
        page = next(pages)
    except StopIteration:
        break
   for user in page:
       print(user.id_str)
       print(user.screen_name)
       print(user.followers_count)
Run Code Online (Sandbox Code Playgroud)

  • `api.followers` 将返回一个用户对象列表,每个对象将包含他们的 id、screen_name 和 follower_count。使用它而不是仅通过 `api.followers_id` 获取他们的 id。 (2认同)