【问题标题】:Searching Tweets in Python在 Python 中搜索推文
【发布时间】:2019-05-06 16:08:32
【问题描述】:

看看下面的代码:

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' 没有定义。

我哪里做错了?

【问题讨论】:

  • 您是否检查过返回的 json 结构是否与您的查询匹配?
  • 没有。我该怎么做?
  • 打印响应,应该是json对象

标签: python twitter


【解决方案1】:

我真的不明白你为什么要这样做

next_results = search_results['search_metadata']['next_results']

而这一行将在 5 次中返回相同的结果?

Anw,“next_results”未定义意味着上面的行甚至没有到达 1 次。

怎么样

print search_results['search_metadata']

查看 API 的响应如何?

【讨论】:

  • 逻辑很直观。结果如下: >>> print search_results['search_metadata'] {u'count': 100, u'completed_in': 0.071, u'max_id_str': u'486716269945569280', u'since_id_str': u'0', u'refresh_url': u'?since_id=486716269945569280&q=%23MentionSomeoneImportantForYou&include_entities=1', u'since_id': 0, u'query': u'%23MentionSomeoneImportantForYou', u'max_id': 486716269945}56928>
  • 所以这里没有'next_results' :) 也许你想要next_results = search_results['search_metadata']['refresh_url']
【解决方案2】:

这段代码完美运行!

# 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))

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 2018-02-24
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2015-12-10
    • 2017-01-07
    • 2018-10-23
    • 2015-11-20
    相关资源
    最近更新 更多