如何在收集推文时修复KeyError'状态'?

问题描述 投票:1回答:2

当我偶然发现这个错误时,我正在使用TwitterAPI收集用户的推文。

由于我计划抓取至少500个具有不同属性的推文,并且每个查询只返回100个推文maxium,我创建了一个函数。

!pip install TwitterAPI
from TwitterAPI import TwitterAPI
import json

CONSUMER_KEY = #ENTER YOUR CONSUMER_KEY
CONSUMER_SECRET = #ENTER YOUR CONSUMER_SECRET
OAUTH_TOKEN = #ENTER YOUR OAUTH_TOKEN
OAUTH_TOKEN_SECRET =  #ENTER YOUR OAUTH_TOKEN_SECRET

api = TwitterAPI(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

这是我的功能如何:

def retrieve_tweets(api, keyword, batch_count, total_count):
    tweets = []
    batch_count = str(batch_count)
    resp = api.request('search/tweets', {'q': 'keyword',
                                         'count':'batch_count', 
                                         'lang':'en',
                                         'result_type':'recent',
                                        }
                      )

    # store the tweets in the list
    tweets += resp.json()['statuses']

    # find the max_id_str for the next batch
    ids = [tweet['id'] for tweet in tweets]
    max_id_str = str(min(ids))

    # loop until as many tweets as total_count is collected
    number_of_tweets = len(tweets)
    while number_of_tweets < total_count:
        print("{} tweets are collected for keyword {}. Last tweet created at {}".format(number_of_tweets, keyword, tweets[number_of_tweets-1]['created_at']))
        resp = api.request('search/tweets', {'q': 'keyword',#INSERT YOUR CODE
                                             'count':'batch_count',
                                             'lang':'en',
                                             'result_type': 'recent',
                                             'max_id': 'max_id_str'
                                            }
                          )

        tweets += resp.json()['statuses']
        ids = [tweet['id'] for tweet in tweets]
        max_id_str = str(min(ids))
        number_of_tweets = len(tweets)

    print("{} tweets are collected for keyword {}. Last tweet created at {}".format(number_of_tweets, keyword, tweets[number_of_tweets-1]['created_at']))
    return tweets

之后,我运行了如下功能:

first_group = retrieve_tweets(api, 'Rock', 100, 500)

它一直运行良好,直到180左右的推文,然后弹出:

179 tweets are collected for keyword Rock. Last tweet created at Mon Apr 29 02:04:05 +0000 2019
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-cbeb6ede7a5a> in <module>
      8 # Your function call should look like this:  retrieve_tweets(api,'keyword',single_count,total_count)
      9 
---> 10 k1_tweets = retrieve_tweets(api, 'Restaurant', 100, 500) #INSERT YOUR CODE HERE
     11 
     12 

<ipython-input-7-0d0c87e7c3e9> in retrieve_tweets(api, keyword, batch_count, total_count)
     55                           )
     56 
---> 57         tweets += resp.json()['statuses']
     58         ids = [tweet['id'] for tweet in tweets]
     59         max_id_str = str(min(ids))

KeyError: 'statuses' 

它应该顺利完成到500,我之前已经多次测试关键字'状态'。

此外,这是在推文收集阶段的不同时间点随机发生的,有一段时间我设法完成了我的第一组500条推文。但是,在第二组的收集过程中会弹出这个错误。此外,当弹出这个错误时,我不能再使用关键'状态',直到我关闭我的编辑器并重新运行它。

这是我在错误发生之前和之后总是运行的简单测试。

a = api.request('search/tweets', {'q': 'Fun', 'count':'10'})
a1 = a.json()
a1['statuses']
python-3.x twitter
2个回答
0
投票

你使用dict.get获取关键statuses的值,如果键不存在则返回None,其他给出关键statuses的值

tweets += resp.json().get('statuses')
if tweets:
    ids = [tweet['id'] for tweet in tweets]
    max_id_str = str(min(ids))
    number_of_tweets = len(tweets)

0
投票

来自Twitter的JSON响应并不总是包含statuses。您还需要处理包含errors密钥的响应。错误响应记录在这里https://developer.twitter.com/en/docs/ads/general/guides/response-codes.html

此外,您的代码使用resp.json()来获取此JSON结构。这很好,但你也可以使用TwitterAPI附带的迭代器。迭代器将迭代statuseserrors中包含的项目。这是用法:

resp = api.request('search/tweets', {'q':'pizza'})
for item in resp.get_iterator():
    if 'text' in item:
        print item['text']
    elif 'message' in item:
        print '%s (%d)' % (item['message'], item['code'])

还有一点你可能没有意识到的是TwitterAPI附带了一个实用程序类,它会连续请求并跟踪max_id。这是一个简短的例子https://github.com/geduldig/TwitterAPI/blob/master/examples/page_tweets.py

© www.soinside.com 2019 - 2024. All rights reserved.