【问题标题】:Twython search API with next_results带有 next_results 的 Twython 搜索 API
【发布时间】:2013-10-19 15:43:33
【问题描述】:

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

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

通过这种方式,我有 15 个状态和 "next_results" 中的 r["metadata"]。有什么方法可以将这些元数据反弹回 Twython API 并进行以下状态更新,或者我应该从"next_results" 手动获取下一个until_id 并执行一个全新的查询?

【问题讨论】:

  • 您使用的是哪个版本的 Twython? Twython 3.1.0 中的搜索方法发生了变化。
  • 我刚刚做了pip install twython 所以我假设我使用的是3.0.0。无论如何,我找到了this 解决方法。
  • 酷。顺便说一句,您可以通过执行以下操作在 python shell 中查看版本: import twython ;打印(twython.__version__)
  • 它说我使用的是 3.1.0 版本。说到这里,我有点迷茫了……
  • 好的,在文档中搜索 Twython 以使用光标功能的更新方法有一点,但我还没有使用它,因此还没有示例代码。 API 搜索功能允许在单个查询中最多显示 100 个结果,但默认情况下只有 15 个。

标签: python api twitter twython


【解决方案1】:

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

【讨论】:

  • 您需要添加 i+=1 吗?
  • 不,for i in range(0,MAX_ATTEMPTS): 语句自动增加计数器...
  • 当我尝试这个时,我只收到了 235 条推文,然后它就坏了。知道为什么吗?
  • 大多数情况下,它会发生,因为没有更多的推文。检查它是从哪里爆发出来的。在步骤 3 的 try 部分打印 i 并在 except 部分打印 next_results_url_params....
  • 刚刚意识到您在第二个 api.search() 语句中错过了 count='100'。这会导致调用在第一个循环后仅检索 15 条推文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 1970-01-01
  • 2014-07-16
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多