【问题标题】:How to unpack JSON provided by tweepy如何解压tweepy提供的JSON
【发布时间】:2020-09-30 02:30:15
【问题描述】:

我使用基于this question 的第一个答案的代码使用 tweepy 抓取推文,如下所示

consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""

import tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)

query = 'kubernetes'
max_tweets = 200
searched_tweets = []
last_id = -1
while len(searched_tweets) < max_tweets:
    count = max_tweets - len(searched_tweets)
    try:
        new_tweets = api.search(q=query, count=count, max_id=str(last_id - 1))
        if not new_tweets:
            break
        searched_tweets.extend(new_tweets)
        last_id = new_tweets[-1].id
    except tweepy.TweepError as e:
        break

它提供了一个json对象的列表,例如searched_tweets[2] 输出(截断)

Status(_api=<tweepy.api.API object at 0x7fc13dbab828>, _json={'created_at': 'Wed Jun 10 14:06:51 +0000 2020', 'id': 1270719075388280834, 'id_str': '1270719075388280834', 'text': "RT @CDWGWAGov: According to @IBM's new CEO, #hybridcloud &amp; #AI are the two dominant forces driving #digitaltransformation #Kubernetes #IoT…", 'truncated': False,

我需要创建日期和推文文本,所以我使用以下代码提取它们

for tweet in searched_tweets:
  new_tweet = json.dumps(tweet)
  dct = json.loads(new_tweet._json)
  created_at=dct['created_at']
  txt=dct['text']

但它给了

TypeError: Object of type 'Status' is not JSON serializable

我已经尝试this 解决这个错误api = tweepy.API(auth, parser=tweepy.parsers.JSONParser()) 它给KeyError: -1 我在stackoverflow上尝试了几乎所有其他解决方案,但对我没有任何帮助。有人可以帮我解压 json 并获得这两个值吗?谢谢

【问题讨论】:

    标签: python json twitter tweepy


    【解决方案1】:

    tweepy 本身的Status 对象不是JSON 可序列化的,但它有一个_json 属性可以被JSON 序列化

    例如

    status_list = api.user_timeline(user_handler)
    status = status_list[0]
    json_str = json.dumps(status._json)
    

    我怀疑错误是由这一行引起的 new_tweet = json.dumps(tweet) 在这里,所以只需在这一行调用_json 属性

    new_tweet = json.dumps(tweet._json)
    

    并修改相关的后续代码。这应该可以解决您的问题

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 2018-11-20
      • 2011-03-31
      • 1970-01-01
      • 2019-12-06
      • 2011-06-28
      • 1970-01-01
      • 2010-10-10
      • 2019-09-30
      相关资源
      最近更新 更多