【问题标题】:Tweepy Streaming - Stop collecting tweets at x amountTweepy Streaming - 停止收集 x 数量的推文
【发布时间】:2014-01-18 18:03:06
【问题描述】:

我希望在 MongoDB 中存储 x # 条推文后,让 Tweepy Streaming API 停止提取推文。

我在类中尝试了 IF 和 WHILE 语句,用计数器定义,但无法让它在某个 X 量处停止。这对我来说是一个真正的头脑风暴。我在这里找到了这个链接:https://groups.google.com/forum/#!topic/tweepy/5IGlu2Qiug4 但我复制它的努力失败了。它总是告诉我 init 需要一个额外的参数。我相信我们的 Tweepy 身份验证设置是不同的,所以它不是苹果对苹果。

有什么想法吗?

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json, time, sys

import tweepy
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

class StdOutListener(StreamListener):

    def on_status(self, status):
        text = status.text
        created = status.created_at
        record = {'Text': text, 'Created At': created}
        print record #See Tweepy documentation to learn how to access other fields
        collection.insert(record)  


    def on_error(self, status):
        print 'Error on status', status

    def on_limit(self, status):
        print 'Limit threshold exceeded', status

    def on_timeout(self, status):
        print 'Stream disconnected; continuing...'


stream = Stream(auth, StdOutListener())
stream.filter(track=['tv'])

【问题讨论】:

    标签: python twitter tweepy


    【解决方案1】:

    您需要在__init__ 的类中添加一个计数器,然后在on_status 中增加它。然后当计数器低于 20 时,它将向集合中插入一条记录。这可以如下所示完成:

    def __init__(self, api=None):
        super(StdOutListener, self).__init__()
        self.num_tweets = 0
    
    def on_status(self, status):
        record = {'Text': status.text, 'Created At': status.created_at}
        print record #See Tweepy documentation to learn how to access other fields
        self.num_tweets += 1
        if self.num_tweets < 20:
            collection.insert(record)
            return True
        else:
            return False
    

    【讨论】:

    • 添加 init 给我这个错误:“'StdOutListener' 对象没有属性 'api'”i.imgur.com/Z2N3hCB.png 我不确定添加与api?
    • 对不起,您还需要添加对基类的 init 的调用。我更新了一下代码,不过就是在init的定义中加一行super(StdOutListener, self).__init__()那么简单。
    • 为了减少将来的错误,我最好将__init__的定义与StreamListener的定义一致:def __init__(self, api=None):,并用api参数调用它。
    • 谢谢,这成功了!所以据我了解,为什么这需要回调基类 init?当我不调用它但添加了 api=None 时,它​​会给出“无属性 api”错误。 super init的目的是回调DOES有api属性的基类吗?
    • 在tweepy中我得到这个错误NameError: global name 'StdOutListener' is not defined我应该如何在init中使用count?
    猜你喜欢
    • 2021-04-19
    • 2018-06-29
    • 1970-01-01
    • 2015-06-27
    • 2019-10-03
    • 1970-01-01
    • 2021-12-27
    • 2022-01-09
    • 2016-06-29
    相关资源
    最近更新 更多