我需要开发一个应用程序,让我跟踪推文,并将其保存在mongodb中,用于一个研究项目(正如你们可能会收集到的,我是一个noob,所以请耐心等待).我发现这段代码可以通过我的终端窗口发送推文:

import sys
import tweepy

consumer_key=""
consumer_secret=""
access_key = ""
access_secret = "" 


auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

class CustomStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print status.text

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['Gandolfini'])

有没有办法修改这段代码,让推文不再在我的屏幕上流动,而是发送到我的mongodb数据库?

谢谢

推荐答案

下面是一个例子:

import json
import pymongo
import tweepy

consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)


class CustomStreamListener(tweepy.StreamListener):
    def __init__(self, api):
        self.api = api
        super(tweepy.StreamListener, self).__init__()

        self.db = pymongo.MongoClient().test

    def on_data(self, tweet):
        self.db.tweets.insert(json.loads(tweet))

    def on_error(self, status_code):
        return True # Don't kill the stream

    def on_timeout(self):
        return True # Don't kill the stream


sapi = tweepy.streaming.Stream(auth, CustomStreamListener(api))
sapi.filter(track=['Gandolfini'])

这将向mongodb test数据库tweets集合发送推文.

希望有帮助.

Mongodb相关问答推荐

通过mongoDB中的查找从管道中删除被阻止的用户

Go mongo-驱动程序测试,FindOne未根据给定的筛选器返回正确结果

联接不返回具有ObjectId和非ObjectId的结果

Golang 无法在 MongoDB 中创建文档

有没有办法从另一条记录中插入一条记录

找到一个用户,然后使用 MongoDB 根据他们的总分获得他们的排名

看起来当我执行 fs.writeFile() 时,更改的文件会重新启动 nodemon.怎么让它不重启?

mongoose通过引用属性查找文档

指定字段对于 MongoDB 是transient瞬态的,但对于 RestController 不是

如何使用 C# MongoDB 驱动程序检索字段子集?

字段类型在 MongoDB 索引中是否重要?

MongoDB:在集合上设置 TTL 索引时出错: sessions

如何将 mongoDB 数据导出为 CSV 格式?

如何对连接到 mongo 的方法进行单元测试,而不实际连接到 mongo?

如何在 mongoDB 中聚合巨大的数组?

如何使用 MongoDB 建模 likes投票系统

在 mongodb 聚合框架中执行 case-statement

Mongoose.pre('save') 不会触发

使用自定义 _id 值时 mongodb 中的 Upserts

如何使用 mongoose 连接到 mongoDB Atlas