Research Tips

研究に関するメモ(専門的すぎない記事を書きたい)

TweepyでフォロワーのIDを全て取得してみた

はじめに

あるTwitterユーザのフォロワーを取得しようと思うと、API制限の壁にぶち当たりました。

例えば、1回あたり5000人分のフォロワーのidを取得できるAPIは15分につき15回なので、5000×15=75000人以上のフォロワーがいるユーザに対して全フォロワーのidを取得することが出来ません。ロッチの中岡さんのアカウントには2016年11月10日現在で101587ユーザのフォロワーがいるのですが、API制限により全フォロワーのidを取得できないのです。twitter.com

で、あれこれ調べていたら、tweepyでAPIインスタンスを生成する際に、wait_on_rate_limit = Trueとすると済むらしい(簡単かよ…)ということが分かったので、それについてメモ。

実装

手順

今回は、フォロワーのidを取ってくるAPIであるAPI.followers_ids(id/screen_name/user_id)を使う。このAPIの概要&注意事項は以下の3点。

  • idで指定されたユーザのフォロワーのユーザidを、一度に最大5000件取得する。
  • 15分につき15回まで呼び出し可能である。
  • Cursorを使って逐次的にフォロワーidを取得する。

つまり、75000人以上フォロワーが存在する場合、75000人の取得につき15分ほどAPIの利用を待機しないといけない。 そこで、APIインスタンスを生成する際に api = tweepy.API(auth, wait_on_rate_limit = True) とすると、「APIの利用制限に引っかかった時に、必要時間だけ待機してくれる」という設定になる。 今回使うAPIは15分につき15回という制限が存在するので、75000人取得する毎に15分待機することになる。

コード

ぐだぐだ言うよりコードを書いた方が早いかもしれない。

# -*- coding:utf-8 -*-
# followers.py

import tweepy

def getApiInstance():

    consumer_key, consumer_secret = "xxxxx", "xxxxx"
    access_token_key, access_token = "xxxxx", "xxxxx"

    auth = tweepy.API(consumer_key, consumer_secret)
    auth.set_access_token(access_token_key, access_token_secret)

    #利用制限にひっかかた時に必要時間待機する
    api = tweepy.API(auth, wait_on_rate_limit = True)

    return api

#Idで指定されたユーザの全フォロワーを取得する
#Id ... ユーザidでもスクリーンネームでもok
def getFollowers_ids(Api, Id):

    #Cursorを使ってフォロワーのidを逐次的に取得
    followers_ids = tweepy.Cursor(Api.followers_ids, id = Id, cursor = -1).items()

    followers_ids_list = []
    try:
        for followers_id in followers_ids:
            followers_ids_list.append(followers_id)
    except tweepy.error.TweepError as e:
        print e.reason

    return followers_ids_list

if __name__ == "__main__":

    screen_name = "lottiso1" #ロッチの中岡さんのアカウントをスクリーンネームで指定する

    api = getApiInstance()
    f_list = getFollowers_ids(Api = api, Id = screen_name)

    print len(f_list) #数で確認してみる
    

Cursorのチュートリアルは原文を要確認です。 http://docs.tweepy.org/en/v3.5.0/cursor_tutorial.html

最後に

今回はAPI.followers_ids(id/screen_name/user_id/)を使ったけど、Cursorに対応しているAPIであれば何でも大丈夫(例:API.followersAPI.friedns_ids、などなど)。 wait_on_rate_limit = TrueとしておけばそれぞれのAPIに合わせて待機時間を変更する(だろう)。 時間はかかる傾向にあるけど、ひとまずこれにて解決。

以上!