-1
def twitter_search(twitter_api,q,max_results=200,**kw):    
    search_results = twitter_api.search.tweets(q=q,count=100,**kw)
    statuses = search_results['statuses']
    max_results=min(1000,max_results)
    for _ in range(10):
        try:
            next_results = search_results['search_metadata']['next_results']
        except KeyError, e:
            break
        kwargs = dict([ kv.split('=')
                for kv in next_results[1:].split("&") ])
        search_results = twitter_api.search.tweets(**kwargs)    
        statuses += search_results['statuses']
        if len(statuses) > max_results:
            break
        return statuses


results = twitter_search(twitter_api,q,max_results=10)
print json.dumps(results[0], indent =1)

The last line is returning an error that 'NoneType' object has no attribute __getitem__

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80

2 Answers2

0

You have two issues here:

  1. The return statement is inside the for loop, and might not be reached if the loop hits one of the break statements first. If it is reached, it will return earlier than you want, without running the rest of the loop iterations.

  2. You are assuming results will have at least one element (results[0]). If results is an empty list, this will fail with an IndexError.

Solution:

  1. Move the return statement outside of the for loop (dedent one level).

  2. Check if results: before indexing into it.

davidism
  • 121,510
  • 29
  • 395
  • 339
0

The problem is q not have trends :S

q =  '#vladimirala1'  


count = 100

search_results = twitter_api.search.tweets(q=q, count =count)

statuses = search_results['statuses']


for _ in range(5):
  print "Length of statuses", len(statuses)
  try:
    next_results = search_results['search_metadata']['next_results']
  except KeyError, e: # No mas resultados si no hay mas datos
    break
  
  kwargs = dict([kv.split('=') for kv in next_results[1:].split('&') ])
  
  search_results = twitter_api.search.tweets(**kwargs)
  
  statuses += search_results['statuses']
  

print json.dumps(statuses[0], indent=1)