具有next_results的Twython搜索API

时间:2013-10-11 14:06:10

标签: python api twitter twython

我对搜索API有点困惑。我们假设我查询“foobar”,代码如下:

from twython import Twython
api = Twython(...)
r = api.search(q="foobar")

通过这种方式,我在"next_results"中拥有15种状态和r["metadata"]。有没有办法将这些元数据退回到Twython API,并且跟随状态更新,或者我可以从until_id手动获取下一个"next_results"和执行一个全新的查询?

1 个答案:

答案 0 :(得分:13)

petrux,“next_results”返回元数据“max_id”和since_id,它们应该用于反弹并循环播放时间线,直到我们得到所需数量的推文。

以下是Twitter上有关如何操作的更新:https://dev.twitter.com/docs/working-with-timelines

下面是可能有用的示例代码。

tweets = []
MAX_ATTEMPTS = 10
COUNT_OF_TWEETS_TO_BE_FETCHED = 500 

for i in range(0,MAX_ATTEMPTS):

    if(COUNT_OF_TWEETS_TO_BE_FETCHED < len(tweets)):
        break # we got 500 tweets... !!

    #----------------------------------------------------------------#
    # STEP 1: Query Twitter
    # STEP 2: Save the returned tweets
    # STEP 3: Get the next max_id
    #----------------------------------------------------------------#

    # STEP 1: Query Twitter
    if(0 == i):
        # Query twitter for data. 
        results = api.search(q="foobar",count='100')
    else:
        # After the first call we should have max_id from result of previous call. Pass it in query.
        results = api.search(q="foobar",include_entities='true',max_id=next_max_id)

    # STEP 2: Save the returned tweets
    for result in results['statuses']:
        tweet_text = result['text']
        tweets.append(tweet_text)


    # STEP 3: Get the next max_id
    try:
        # Parse the data returned to get max_id to be passed in consequent call.
        next_results_url_params = results['search_metadata']['next_results']
        next_max_id = next_results_url_params.split('max_id=')[1].split('&')[0]
    except:
        # No more next pages
        break