使用python

时间:2015-08-10 13:25:10

标签: python json mongodb twitter

我正在尝试使用以下代码将推文搜索结果插入MongoDB:

import json
import tweepy

from pymongo import MongoClient

ckey = ''
consumer_secret = ''
access_token_key = ''
access_token_secret = ''

auth = tweepy.OAuthHandler(ckey, consumer_secret)
auth.set_access_token(access_token_key, access_token_secret)

api = tweepy.API(auth)

for data in tweepy.Cursor(api.search,q='test',since='2015-08-01',until='2015-08-10').items():
    client = MongoClient('localhost', 27017)
    db = client['twitter_db']
    collection = db['twitter_collection']
    tweet_json = json.loads(data)
    collection.insert(tweet_json)

但是在将结果解析为JSON时我得到了错误消息:

Traceback (most recent call last):
  File "twitter_past.py", line 28, in <module>
    tweet_json = json.loads(data)
  File "//anaconda/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "//anaconda/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

是否有以JSON格式插入好东西的想法?

1 个答案:

答案 0 :(得分:1)

因为光标没有返回JSON。它返回tweepy.models.Status模型的实例。它显然不能被解析为JSON。

要从模型中获取解析的JSON,您可以使用data._json