twitterのAPIを触ってみる No.3(フォロワーとフォローの取得)

フォロワーとフォローしている人を取得してみたいと思います.

 

 

参考記事

tmngtm.hatenablog.com

また,大量のフォロワーを取得することを考えて認証を自動で再度行ってれるように以下のサイトを参考にしました

qiita.com

 

1.フォロワーの取得

import tweepy
import yousan_config

auth = tweepy.OAuthHandler(yousan_config.consumer_key,
yousan_config.consumer_secret)
auth.set_access_token(yousan_config.access_token,
yousan_config.access_token_secret)

api = tweepy.API(auth)
# name = input("検索のしたいユーザー名を入れてください:")
name = 'ayousanz'
# followerList =

# api = tweepy.API(auth, wait_on_rate_limit=True)
cursor = -1
i = 0
followerNumber = 0
while cursor != 0:
# APIインスタンスを生成
itr = tweepy.Cursor(api.followers_ids, id=name, cursor=cursor).pages()
# followerNumber = itr.next()
for follower_id in itr.next():
# print(i + "/" + followerNumber)
try:
user = api.get_user(follower_id)
user_info = [user.id_str, user.screen_name, user.name, user.created_at]
# followerList.append(user.screen_name)
# print(user_info)
print(str(i) + ":"+ user.screen_name)
i = 1 + i
except tweepy.error.TweepError as e:
print(e.reason)
cursor = itr.next_cursor

# これで,フォロワーの情報を取得する
# print("フォロワー名:" + followerList)

これで,

f:id:ka1357amnbpdr:20190901172947p:plain

こんな感じに表示をしてくれます

 

2.フォローしている人の取得

import tweepy
import yousan_config

auth = tweepy.OAuthHandler(yousan_config.consumer_key,yousan_config.consumer_secret)
auth.set_access_token(yousan_config.access_token,yousan_config.access_token_secret)

api = tweepy.API(auth)
# name = input("検索のしたいユーザー名を入れてください:")
name = 'ayousanz'
# followerList =
cursor = -1
i = 0
while cursor != 0:
# APIインスタンスを生成
itr = tweepy.Cursor(api.friends_ids, id=name, cursor=cursor).pages()
# followerNumber = itr.next()
for friends_id in itr.next():
# print(i + "/" + followerNumber)
try:
user = api.get_user(friends_id)
user_info = [user.id_str, user.screen_name, user.name, user.created_at]
# followerList.append(user.screen_name)
# print(user_info)
print(str(i) + ":"+ user.screen_name)
i = 1 + i
except tweepy.error.TweepError as e:
print(e.reason)
cursor = itr.next_cursor

# 自分がフォローしてるユーザーを取得する

こちらで,以下のように自分のフォローをしている人を取得できます

f:id:ka1357amnbpdr:20190901173113p:plain 

前回の記事

 

ayousan.hatenablog.com

 

関連記事

 

ayousan.hatenablog.com