LoginSignup
0
1

More than 1 year has passed since last update.

Google ColaboratoryでTwitter APIを動かしてみた

Posted at

背景

Twitter APIを利用する方法を調べていると、Tweepyというライブラリで簡単に実装できたので紹介します。
Google Colaboratoryで実行し環境構築も楽なのでおすすめです。

今回はAPIでユーザー名、ツイート日時、位置情報、ツイート文を取得しcsvファイルで保存します。

前提

TwitterDeveloperの申請を行いAPIを呼び出せる準備が整っていることを前提にします。
申請方法は他の記事をご覧ください。

Google Colaboratoryでtweepyをインストール

pip install tweepy

次に特定のワードを含むツイートの取得するコードが下記になります。
api_key、api_secret、access_token、access_secretはそれぞれTwitter Developer Platform上で確認できる各自のキーを入力してください。

twitterAPI.py
    import tweepy
    import csv
    from collections import namedtuple
    from datetime import timedelta # 日本時間に直すために使用
    
    api_key = ''
    api_secret = ''
    access_token = ''
    access_secret = ''
    
    auth = tweepy.OAuthHandler(api_key,api_secret)
    auth.set_access_token(access_token,access_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) # ツイート取得の制限になった場合に15分中断する
    
    fetch_date = "07-01" # ツイートを取得する日を設定(例)7月1日の時 07-01
    
    word = '-bot -RT テスト since:2022-%s_00:00:00_JST until:2022-%s_23:59:59_JST' % (fetch_date, fetch_date)
    maxid = 0
    
    f = open('twitterAPI_%s.csv' % fetch_date, 'w',encoding='UTF-8')
    tweetDataList = []
    
    while True:
        result = api.search(q=word, lang='ja', count=100, max_id=maxid)
        print(len(result))
        if len(result)==0:
            break
        for res in result:
            maxid = res.id-1
            sc_name = res.user.screen_name # @ユーザー名
            name = res.user.name # プロフィール名
            desc = res.user.description # 自己紹介文
            text = res.text.replace('\n', '') # ツイート文
            datetime = res.created_at + timedelta(hours=9) # 日本時間に変換
            location = res.place # 位置情報
    
            if 'bot' in name.lower() or 'bot' in desc.lower(): # 紹介文と名前にBOTを除く
                continue
    
            tweetDataList.append([f'{sc_name}', f'{datetime}', f'{location}', f'{text}'])
    
        print(datetime)
    
    writer = csv.writer(f,  lineterminator="\n")
    writer.writerow(["sc_name", "datetime", "location", "text"])
    writer.writerows(tweetDataList)
    
    f.close()

このコードでは'テスト'というキーワードを含むツイートの取得ができます。
キーワード部分を変更することで複数のワードを含むツイートの検索も可能です。
(例)
・'野菜'と'価格'の2つのキーワードを含むツイートを検索

野菜 AND 価格

・'野菜'または'価格'のいずれかのキーワードを含むツイートを検索

野菜 OR 価格

ツイート数が多いキーワードの場合実行に時間がかかるため、テストで行う場合はツイート数の少なそうなワードにするか、日付の部分を00:00:00 → 23:00:00等に変更すると1時間分のツイートだけ取得できます。

0
1
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
0
1