Reputation: 33
I'm super new to Python but I am trying to access the Twitter API to pull in the number of followers for a list of twitter handles (or user IDs - i have both datasets) and print them to a csv file. I've searched for quite some time for this but haven't found anything that has truly worked.
This is what I currently 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 here are:
Can I have all the targets in a pre populated file and have the follower count for each target print out in the column next to the IDs?
How do I add in count-break since: The twitter API only allows 100 users to be searched for at a time...[so] what you'll need to do is iterate through each 100 users but staying within the rate limit.
Apologies if this is super basic and thanks in advance for any help!
Upvotes: 3
Views: 2901
Reputation: 8047
Summarizing 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 contents:
99795204
973058420
988290763
984965461
973058420
97074741
969892964
968396750
Upvotes: 1