
121
5.5 データのスクレイピング
import json
# ...
class MyStreamListener(StreamListener):
"""
ツイートをストリーミングして
MongoDB
データベースに保存する
"""
def _ _init_ _(self, api, **kw):
self.api = api
super(tweepy.StreamListener, self)._ _init_ _()
†
self.col = get_mongo_database('tweets', **kw)['tweets'] #
❶
def on_data(self, tweet):
self.col.insert(json.loads(tweet)) #
❷
def on_error(self, status):
return True #
ストリームを開いたままにする
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
stream = tweepy.Stream(auth, MyStreamListener(api))
#
キーワードのトラックリストでストリームを開始する
stream.filter(track=['python', 'javascript', ...