daniyal.bashir daniyal.bashir - 5 months ago 21
Python Question

Getting Twitter Followers using Twitter's REST API

I am using python script to get the followers for a specific user. The script runs perfectly and it returns the IDs of the followers when i use user lookup API it only returns 3 result. The script is like this:

#!/usr/bin/python


from twitter import *

import sys
import csv
import json

config = {}
execfile("/home/oracle/Desktop/twitter-1.17.1/config.py", config)

twitter = Twitter(
auth = OAuth(config["access_key"], config["access_secret"],config["consumer_key"], config["consumer_secret"]))

username = "#####"

query = twitter.followers.ids(screen_name = username)

print "found %d followers" % (len(query["ids"]))

for n in range(0, len(query["ids"]), 100):
ids = query["ids"][n:n+100]

subquery = twitter.users.lookup(user_id = ids)
for user in subquery:

print " [%s] %s" % ("*" if user["verified"] else " ", user["screen_name"])
# print json.dumps(user)


And it returns the output like this:

{u'next_cursor_str': u'0', u'previous_cursor': 0, u'ids': [2938672765, 1913345678, 132150958, 2469504797, 2162312397, 737550671029764097, 743699723786158082, 743503916885737473, 742612685632770048, 742487358826811392, 742384945121878020, 741959985127665664, 1541162424, 739102973830254592, 740198523724038144, 542050890, 739971273934176256, 2887662768, 738922874011013120, 738354749045669888, 737638395711791104, 737191937061584896, 329618583, 3331556957, 729645523515396096, 2220176421, 162387597, 727099914635874304, 726665274737475584, 725406360406470657, 938760691, 715260034335305729, 723912842320158720, 538208881, 2188791158, 723558257541828608, 1263571466, 720182865275842564, 719947801598259200, 636067084, 719412219168038912, 719199478260043776, 715921761158574080........ ], u'next_cursor': 0, u'previous_cursor_str': u'0'}


When i use the user look up API it only returns 4 screen names like this:


found 1106 followers
[ ] In_tRu_dEr
[ ] amanhaider3
[ ] SaaddObaid
[ ] Soerwer


I want the screen names of all the IDs present but it returns only 4. Can anyone help.

Answer

your issue is in those 2 lines

(I assumed second line is intended although it is not in the question)

for n in range(0, len(query["ids"]), 100):
    ids = query["ids"][n:n+100]

those lines will create multi ids arrays and they overwrite each other

so first iteration ids will have the ids from 0 to 100

then you overwrite it with ids from 100 to 200 and so on

till you reach last iteration from 1100 to 1106

so ids will only have ids on it

and apprenatly from those 6 only 4 are returned by twitter.users.lookup

to fix it you will need to keep everything under the for n loop like this

for n in range(0, len(query["ids"]), 100):
    ids = query["ids"][n:n+100]

    subquery = twitter.users.lookup(user_id = ids)
    for user in subquery:

        print " [%s] %s" % ("*" if user["verified"] else " ", user["screen_name"])

this will work

Comments