我正在尝试使用这种方法保存Twitter API获得的一些数据:
def getTweets(usuario):
api = Autentificacion.autentificacion()
usuari = api.get_user(usuario)
dic = {}
page_list = []
for page in tweepy.Cursor(api.user_timeline, id=usuario, count=200).pages(16):
page_list.append(page)
for page in page_list:
for status in page:
id_tweet = str(status.id)
tweet = {usuari.screen_name, status.text, status.created_at}
try:
dic[id_tweet]= tweet
except (KeyError, TypeError, ValueError):
print "Error al introducir datos en el diccionario"
try:
datos = Controles()
datos.saveOnBD(dic)
except PyMongoError, e:
print "Error: ", e
方法 saveOnDB(dic)
def saveOnBD(self, dic):
client = MongoClient('server', port)
db = client.DB_Tweets_User_Date
collection = db.tweets
collection.insert_one(dic)
这就是追溯:
...
collection.insert_one(dic)
File "C:\Python27\lib\site-packages\pymongo\collection.py", line 467, in insert_one
return InsertOneResult(self._insert(sock_info, document),
File "C:\Python27\lib\site-packages\pymongo\collection.py", line 430, in _insert
gen(), check_keys, self.codec_options, sock_info)
bson.errors.InvalidDocument: Cannot encode object: set([u'That is a testing tweet', datetime.datetime(2015, 7, 2, 8, 23, 30), u'user'])
我发现了许多类似的问题,但解决方案对我没有用。
答案 0 :(得分:2)
The error message
bson.errors.InvalidDocument: Cannot encode object: set([u'That is a testing tweet', datetime.datetime(2015, 7, 2, 8, 23, 30), u'user'])
shows that you are setting an invalid object in your code.
The bug is in this line, which is Python 2.7+ syntax for a Python set:
tweet = {usuari.screen_name, status.text, status.created_at}
to this, which creates a dict:
tweet = {'screen_name': usuari.screen_name, 'text': status.text, 'created_at': status.created_at}