查看以下代码:
q = '#MentionSomeoneImportantForYou'
count = 100
search_results = twitter_api.search.tweets(q=q, count=count)
#twitter_api
已预定义且工作正常。
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 more results when next_results doesn't exist
break
kwargs = dict([ kv.split('=') for kv in next_results[1:].split("&") ])
最后一个代码抛出错误,即“next_results”未定义。
我在哪里出错?
答案 0 :(得分:0)
我真的不明白为什么你必须
next_results = search_results['search_metadata']['next_results']
虽然这一行会在5次内返回相同的结果吗?
Anw," next_results"没有定义意味着上面的行甚至没有达到一次。
怎么样
print search_results['search_metadata']
确切了解API的响应情况如何?
答案 1 :(得分:0)
此代码完美运行!
# Import unquote to prevent url encoding errors in next_results
from urllib.parse import unquote
q='#Ethiopia'
count = 100
# See https://dev.twitter.com/docs/api/1.1/get/search/tweets
search_results = twitter_api.search.tweets(q=q, count=count)
statuses = search_results['statuses']
# Iterate through 5 more batches of results by following the cursor
print(search_results['search_metadata'])
for _ in range(5):
print("Length of statuses", len(statuses))
try:
#print(search_results['search_metadata'])
next_results = search_results['search_metadata']['next_results']
except KeyError: # No more results when next_results doesn't exist
break
# Create a dictionary from next_results, which has the following form:
# ?max_id=313519052523986943&q=NCAA&include_entities=1
kwargs = dict([ kv.split('=') for kv in unquote(next_results[1:]).split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
# Show one sample search result by slicing the list...
print(json.dumps(statuses[0], indent=1))