2016-11-10 7 views
1

Twitterのデータを扱うpythonスクリプトを作成しようとしていますが、幸運はありません!私は何が間違っているのか分かりませんMongoDB Python Twitterのストリーミングがデータベースに保存されない

from pymongo import MongoClient 
import json 
from tweepy import Stream 
from tweepy import OAuthHandler 
from tweepy.streaming import StreamListener 
import datetime 

# Auth Variables 

consumer_key = "INSERT_KEY_HERE" 
consumer_key_secret = "INSERT_KEY_HERE" 
access_token = "INSERT_KEY_HERE" 
access_token_secret = "INSERT_KEY_HERE" 

# MongoDB connection info 

connection = MongoClient('localhost', 27017) 
db = connection.TwitterStream 
db.tweets.ensure_index("id", unique=True, dropDups=True) 
collection = db.tweets 

# Key words to be tracked, (hashtags) 

keyword_list = ['#MorningAfter', '#Clinton', '#Trump'] 


class StdOutListener(StreamListener): 
    def on_data(self, data): 

     # Load the Tweet into the variable "t" 
     t = json.loads(data) 

     # Pull important data from the tweet to store in the database. 
     tweet_id = t['id_str'] # The Tweet ID from Twitter in string format 
     text = t['text'] # The entire body of the Tweet 
     hashtags = t['entities']['hashtags'] # Any hashtags used in the Tweet 
     time_stamp = t['created_at'] # The timestamp of when the Tweet was created 
     language = t['lang'] # The language of the Tweet 

     # Convert the timestamp string given by Twitter to a date object called "created" 
     created = datetime.datetime.strptime(time_stamp, '%a %b %d %H:%M:%S +0000 %Y') 

     # Load all of the extracted Tweet data into the variable "tweet" that will be stored into the database 
     tweet = {'id': tweet_id, 'text': text, 'hashtags': hashtags, 'language': language, 'created': created} 

     # Save the refined Tweet data to MongoDB 
     collection.insert(tweet) 

     print(tweet_id + "\n") 
     return True 

    # Prints the reason for an error to your console 
    def on_error(self, status): 
     print(status) 

l = StdOutListener(api=tweepy.API(wait_on_rate_limit=True)) 
auth = OAuthHandler(consumer_key, consumer_key_secret) 
auth.set_access_token(access_token, access_token_secret) 

stream = Stream(auth, listener=l) 
stream.filter(track=keyword_list) 

これまで私が持っていたスクリプトです。私はいくつかのGoogleの検索をしようとしたし、私は彼らが持っているものと比較し、問題の原因を見つけることができません。それは実行され、MongoDBに接続する、私は正しいデータベースを作成したが、何もデータベースに配置されていません。私はtweet idを出力するデバッグコードを少し持っていますが、それは約5〜10秒の間隔で401を何度も繰り返し表示します。私は私がやりたいことをグーグルで見つけながら、まだ何も起こっていない、私が見つけたいくつかの基本的な例を試しました。私はそれがデータベース接続の問題かもしれないと思いますか?ここには、実行されているデータベースのいくつかのイメージがあります。 This is with the database just started This is with the script running アイデアをいただければ幸いです。ありがとうございました!

答えて

0

私はそれを最終的に考え出しました!ここでは401の印刷が鍵であり、認証エラーです。システムクロックをインターネットに接続し、システムのクロックをリセットする必要がありました。

関連する問題