user9663765
user9663765

Reputation:

Get list of followers and following for group of users tweepy

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()

Upvotes: 9

Views: 14081

Answers (1)

jschnurr
jschnurr

Reputation: 1191

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)

Upvotes: 16

Related Questions