LoginSignup
2
3

More than 3 years have passed since last update.

tweepyを使ったtwitterデータ取得1

Last updated at Posted at 2019-09-10

twitterからデータ取得やってみる

■背景・目的

  • 背景

    • Twitterを使ったデータ分析をやりたいものの、どのようなデータが取得できてるかわからないので、データ取得をまずやってみる
  • 目的

    • まずはtweepyで実装して、以下を明らかにしたい
      • twitterのAPIを使って取得したデータはどのような形式か←今回はここ
      • API取得したデータの前処理方法
      • 加工データを使ったデータ分析

■nikeとadidasという単語を含むツイートを保存する

twitter_api1.py
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

#twitter apiの認証情報を別ファイルに保存し、インポートする
import get_data.twitter_credentials as credentials
# リスナーと認証オブジェクトを生成し、Streamオブジェクトに渡してあげると、ツイートを読み込める
class TwitterStreamer():
    """
    ライブのツイートをストリーム処理するクラス
    """
    def __init__(self):
        pass


    def stream_tweets(self,fetched_tweets_filename,hash_tag_list):
    # This handles Twitter authentication and the connection to the Twitter Streaming API
        listener = StdOutListener(fetched_tweets_filename)
        auth = OAuthHandler(credentials.consumer_key, credentials.consumer_secret)
        auth.set_access_token(credentials.Access_token, credentials.Access_secret)
        stream = Stream(auth, listener)
        stream.filter(track=hash_tag_list)



#streamListenerを継承して、新たにリスナーオブジェクトを作成
class StdOutListener(StreamListener):
    """
    基本のリスナークラス:受け取ったツイートをそのまま出力する
    """
    def __init__(self,fetched_tweets_filename):
        self.fetched_tweets_filename=fetched_tweets_filename


    def on_data(self,data):
        try:
            print(data)
            with open(self.fetched_tweets_filename,'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Eror on data: &s" % str(e))
        return True

        print(data)
        return True

    def on_error(self, status):
        print(status)

if __name__ =="__main__":
    hash_tag_list=["nike","adidas"]
    fetched_tweets_filename="tweets.json"


    twitter_streamer=TwitterStreamer()
    twitter_streamer.stream_tweets(fetched_tweets_filename,hash_tag_list)```

```python:twitter_credentials.py
#token取得方法は参考リンクを確認
consumer_key="コンシューマーキー"
consumer_secret="コンシューマー秘密"

Access_token="アクセストークン"
Access_secret="アクセスシークレット"

■わかったこと

  • Streamクラスにauthとlistnerを突っ込み、streamオブジェクトでツイートストリームを取れる。(日本語の単語だとなぜか遅いけどなんで?)
  • JSONで値が返ってくるので、JSONの前処理してから、データ分析する流れになりそう

■疑問、課題点

- いまのところなし

■改善点

■参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3