2016-11-10 48 views
1

試圖創建一個python腳本,將datamine twitter,但我沒有好運!我不知道我在做什麼錯MongoDB蟒蛇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) 

這是我到目前爲止的腳本。我試圖做一些谷歌搜索,我比較了我有什麼,他們有什麼,不能找到問題的根源。它運行並連接到MongoDB,我創建了正確的數據庫,但數據庫中沒有任何內容。我有一些調試代碼,它打印鳴叫ID,但它只是在大約5-10秒的時間間隔內反覆打印401。我嘗試了一些基本的例子,當我用Google搜索的時候發現了它,但仍然沒有發生任何事情。我認爲這可能是數據庫連接的問題?這裏是正在運行的數據庫的一些圖像。 This is with the database just started This is with the script running 任何想法將不勝感激,謝謝!

回答

0

我終於明白了! 401的打印是關鍵,這是一個認證錯誤。我不得不將我的系統時鐘連接到互聯網,並重置我的系統時鐘。