Python中的推文

时间:2014-07-10 13:17:57

标签: python search twitter tweets

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)

最后一行返回'NoneType' object has no attribute __getitem__

的错误

2 个答案:

答案 0 :(得分:0)

这里有两个问题:

  1. return语句位于for循环内,如果循环首先命中break个语句之一,则可能无法访问。如果达到它,它将比你想要的更早返回,而不运行其余的循环迭代。

  2. 您假设results至少有一个元素(results[0])。如果结果为空列表,则会因IndexError而失败。

  3. 解决方案:

    1. return语句移到for循环之外(dedent one level)。

    2. 在编入索引前检查if results:

答案 1 :(得分:0)

问题是q没有趋势: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)