Get list of followers and following for group of users tweepy

Question:

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()
Asked By: user9663765

||

Answers:

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.get_friends, screen_name="TechCrunch").items():
    print('friend: ' + user.screen_name)

for user in tweepy.Cursor(api.get_followers, screen_name="TechCrunch").items():
    print('follower: ' + user.screen_name)
Answered By: jschnurr
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.