如何使用Twitter的流API消费推文并将其存储在MongoDB中

20

我需要开发一个应用程序,可以让我跟踪推文并将它们保存在 MongoDB 中,以供研究项目使用(正如您所了解的,我是个新手,请多包涵)。我找到了一段代码,可以通过终端窗口发送推文流:

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数据库中?

谢谢


请注意:以下代码来自http://peter-hoffmann.com/2012/simple-twitter-streaming-api-access-with-python-and-oauth.html。 - user2161725
2个回答

18

这里有一个例子:

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集合中。
希望对您有所帮助。

是的,这似乎可以工作。非常感谢。我想下一个问题是:如何修改您提供的脚本,以便将推文发送到托管在MongoLab上的远程数据库,而不是发送到我的本地mongodb?有什么想法吗?再次感谢! - user2161725
1
当然,pymongo.MongoClient接受hostport参数。请参阅文档 - alecxe
首先,代码非常好用。我玩得很开心,感谢你。如果我想跟踪一个位置而不是一个单词,我该怎么做?我试着替换代码的最后一行,让它变成sapi.filter(locations=['-74,40,-73,41']),但是出现了AssertionError错误。你有什么想法可以解决这个问题吗?谢谢! - user2161725
locations 参数应该是一个长度为 4 的列表,例如 ['-74','40','-73','41']。可以吗? - alecxe
是的。具体来说,它可以通过将最后一行更改为sapi.filter(locations=[-74, 40, -73, 41])来工作,即不在纬度/经度对周围加上引号。再次感谢。 - user2161725
关于将推文发送到远程数据库,我需要修改的唯一代码就是将 "self.db = pymongo.MongoClient().test" 更改为 "self.db = pymongo.MongoClient(host:port).test",是这样吗? - user2161725

6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接