Twitter API - Followers Count for Multiple Users
I'm super new to Python, but I'm trying to access the Twitter API to get the follower count for a list of twitter pens (or user IDs - I have both datasets) and print them out to a csv file. I've searched long enough for this but haven't found anything that actually worked.
This is what I have:
import tweepy
import time
import csv
import sys
# Keys, tokens and secrets
consumer_key = 'REMOVED'
consumer_secret = 'REMOVED'
access_token = 'REMOVED'
access_token_secret = 'REMOVED'
# Tweepy OAuthHandler
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
targets = [12345,123456] # All your targets here
for target in targets:
user = api.get_user(target)
print(user.name, user.followers_count)
My questions are here:
-
Can I have all targets in a pre-filled file and count the number of followers for each target print in the column next to the IDs?
-
How to add to count-break with: The twitter API allows you to search for 100 users at the same time ... [so] what you need to do is iterate over every 100 users, but stay within the speed limit.
Sorry if this is super basic and thanks in advance for any help!
source to share
Summing up the discussion in the comments:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import tweepy
import time
import unicodecsv as csv
import codecs
import sys
reload(sys)
sys.setdefaultencoding('utf8')
access_token = ''
access_token_secret = ''
consumer_key = ''
consumer_secret = ''
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True)
with open('targets.txt', 'r') as targets_file:
targets_list = targets_file.readlines()
targets_list_filtered = filter(None, targets_list[0].split('\r'))
targets_list_cleaned = []
for item in targets_list_filtered:
targets_list_cleaned.append(item.strip('\n'))
with codecs.open('output.csv', 'wb', 'utf-8') as outcsv:
outfile = csv.DictWriter(outcsv, encoding='utf-8', fieldnames=['uID', 'Username', 'Follower Count', 'Verified'])
outfile.writeheader()
for idx, target in enumerate(targets_list_cleaned):
try:
user = api.get_user(target)
outfile.writerow({'uID': target, 'Username': user.name, 'Follower Count': user.followers_count, 'Verified': user.verified})
print idx, target, user.name, user.followers_count, user.verified
except tweepy.TweepError as e:
# outfile.writerow(e.message)
print idx, target, e.message
example targets.txt
file content:
99795204 973058420 988290763 984965461 973058420 97074741 969892964 968396750
source to share