【问题标题】:How can I consume tweets from Twitter's streaming api and store them in mongodb我如何使用 Twitter 的流 api 中的推文并将它们存储在 mongodb 中
【发布时间】:2013-06-17 07:56:02
【问题描述】:

我需要开发一个应用程序,让我可以跟踪推文并将它们保存在 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 数据库?

谢谢

【问题讨论】:

标签: python mongodb twitter pymongo tweepy


【解决方案1】:

这是一个例子:

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,而是将它们发送到托管在 MongoLab 上的远程数据库?有什么想法吗?再次感谢!
  • 当然,pymongo.MongoClient 接受 hostport 参数。见docs
  • 首先,代码就像一个魅力。我玩得很开心,所以谢谢你。如果我不想跟踪一个单词,而是想跟踪一个位置,我该怎么做?我尝试替换最后一行代码,使其读取 sapi.filter(locations=['-74,40,-73,41']) 但得到一个 AssertionError。知道如何解决这个问题吗?谢谢!
  • locations 参数应该是长度为 4 的列表,例如['-74', '40', '-73', '41']。有效吗?
  • 是的。具体来说,它可以将最后一行更改为 sapi.filter(locations=[-74, 40, -73, 41]) ,即在 lat/long 对周围没有吓人的引号。再次感谢。
【解决方案2】:

我已经开发了一个简单的命令行工具来完成这个任务。

https://github.com/janezkranjc/twitter-tap

它允许使用流 API 或搜索 API。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多