[英]How to stop Tweepy once X amount of tweets have been stored in CSV?
[英]Tweepy Streaming - Stop collecting tweets at x amount
我想在MongoDB中存儲x#推文之后,讓Tweepy Streaming API停止推文。
我已經在類中嘗試了IF和WHILE語句,使用計數器進行了定義,但是無法讓它在某個X量上停止。 對我來說,這真是一個真正的頭腦。 我在這里找到了這個鏈接: https : //groups.google.com/forum/#!topic / tvweepy / 5IGlu2Qiug4但是我復制這個的努力失敗了。 它總是告訴我init需要一個額外的參數。 我相信我們的Tweepy auth設置不同,所以它不是蘋果到蘋果。
有什么想法嗎?
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'])
你需要在__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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.