Get list of followers and following for group of users tweepy

10,302

Tweepy is a wrapper around the Twitter API.

According to the Twitter API documentation, you'll need to call the GET friends/ids to get a list of their friends (people they follow), and GET followers/ids to get their followers.

Using the wrapper, you'll invoke those API calls indirectly by calling the corresponding method in Tweepy.

Since there will be a lot of results, you should use the Tweepy Cursor to handle scrolling through the pages of results for you.

Try the code below. I'll leave it to you to handle the CSV aspect, and to apply it to multiple users.

import tweepy

access_token = "1234"
access_token_secret = "1234"
consumer_key = "1234"
consumer_secret = "1234"

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

for user in tweepy.Cursor(api.friends, screen_name="TechCrunch").items():
    print('friend: ' + user.screen_name)

for user in tweepy.Cursor(api.followers, screen_name="TechCrunch").items():
    print('follower: ' + user.screen_name)
Share:
10,302
Admin
Author by

Admin

Updated on June 28, 2022

Comments

  • Admin
    Admin almost 2 years

    I was just wondering if anyone knew how to list out the usernames that a twitter user is following, and their followers in two separate .csv cells. This is what I have tried so far.

    import tweepy
    import csv
    
    consumer_key = ""
    consumer_secret = ""
    access_token = ""
    access_token_secret = ""
    
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    
    api = tweepy.API(auth)
    
    csvFile = open('ID.csv', 'w')
    csvWriter = csv.writer(csvFile)
    
    users = ['AindriasMoynih1', 'Fiona_Kildare', 'daracalleary', 'CowenBarry', 'BillyKelleherTD', 'BrendanSmithTD']
    
    
    for user_name in users:
        user = api.get_user(screen_name = user_name, count=200)
        csvWriter.writerow([user.screen_name, user.id, user.followers_count, user.followers_id, user.friends_id user.description.encode('utf-8')])
        print (user.id)
    
    
    csvFile.close()
    
  • Admin
    Admin over 5 years
    That's perfect, thank you! Although I am getting a rate limit exceeded error. How would I be able to get all of the users without getting this error?
  • jschnurr
    jschnurr over 5 years
    Try api = tweepy.API(auth, wait_on_rate_limit=True) ; that will tell Tweepy to pause until the rate limit expires, instead of giving an error.
  • plutownium
    plutownium about 2 years
    Tweepy now has api.get_friends instead of api.friends . Source: docs.tweepy.org/en/stable/api.html#tweepy.API.get_friends