LoginSignup
1

More than 1 year has passed since last update.

Twitter APIを利用してデータを取得する!

Last updated at Posted at 2022-02-05

 初めに

TwitterAPIを利用してデータを取得してデータ分析ゼロからしたい!というモチベーションで行っています!まずは何も決まっていないので、TwitterAPIの取得から行っていきたいと思います!

 Twitter API v2を使用するために

Twitterのデータを効率的に取得するためには、Twitter APIの利用が欠かせません。このTwitter APIを利用するには、Twitterの開発者申請が必要になります。

Twitterにログインした状態で
https://developer.twitter.com/en/apps/
に入り、「Create an app」ボタンをクリックします。

  • アカウント(自分の)
  • メールアドレス(自分の)
  • What's your name?(自分の)
  • What country are you based in?(自分の)
  • What's your use case? ->Exploring the API
  • Will you make Twitter content or derived information available to a government entity or a government affiliated entity? ->No

としてNextを選択しました。
次に「Developer agreement & policy」を読み、Submitします。するとSuccess! Application submitted. Your application has been submitted successfully.と出るのでメールを確認して、認証します。

APIを利用するためのAPIキーが表示されます。

API key
xxxxxxxxxxxxxxxxxxxxxxxxxx
API key Secret
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Bearer Token
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

APIキーは同じものは二度と表示されないので、必ず控えておきます。
次に、Developer Portalに戻り、ユーザー認証を行います。

「User Authentication Setting」の「Set up」をクリック

「Auth 1.0a」にチェック

Callback URLを追記https://127.0.0.1:3000/cb

https://twitter.com/自分のIDの@以下を追記

Save

「OAth 1.0a turned on」と緑色のチェックを確認して、APIキー・トークンの再取得していきます。Twitter APIを使う時には以下の4つが必要になります。

  • APIキー
  • APIトークン
  • アクセスキー
  • アクセストークン

アクセスキーとアクセストークンはDeveloper portalのダッシュボードから確認します。

取得できるツイートの制限について事前に確認しておきます

コードを実際に実行したら

Forbidden: 403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve

が出るので、ここにアクセスして、Elevated アクセスを申請します。(どうやらEssentialからElevatedというものにならないといけないらしいです)

私は3回の申請

を行なって、合計2日くらいかかりましたが、無事に承認されました(88888)。

  • OAuth 2.0を有効にする
  • Type of AppをとりあえずWeb Appにする
  • Request email from users (optional)をRead and write and Direct messageにする
  • Callback URIとWebSite URLを設定する

すると
Changing permissions might affect your App
Are you sure you want to change permissions?
と聞かれるので
Yesと答えます。

Client IDとClient Secretを保存します。

データ取得

私が約1ヶ月使用していたTwitterデータ取得の方法を2つ以下に示します!

tweepy

WOEIDはWhere On Earth IDentifierのことで、世界の国、都市に一意に振られたIDです。Twitter APIではこのWOEIDを利用して、特定の地域のトレンドを取得することができます。WOEIDは世界中のどの都市にも割り当てられているわけではありません。

日本では以下の都市に割り振られています。

日本 23424856
東京 1118370
横浜 1118550
千葉 1117034
福岡 1117099
浜松 1117155
広島 1117227
川崎 1117502
北九州 1110809
神戸 1117545
熊本 1117605
京都 15015372
名古屋 1117817
新潟 1117881
岡山 90036018
沖縄 2345896
大阪 15015370
相模原 1118072
埼玉 1116753
札幌 1118108
仙台 1118129
高松 1118285

import tweepy

API_Key     = "*************************"
API_Sec     = "**************************************************"
Token       = "**************************************************"
Token_Sec   = "*********************************************"

# Twitterオブジェクトの生成
auth = tweepy.OAuthHandler(API_Key, API_Sec)
auth.set_access_token(Token, Token_Sec)
api = tweepy.API(auth)

#日本のWOEID
woeid = 23424856
#トレンド一覧取得
trends = api.get_place_trends(woeid)

#データフレームに変換
import pandas as pd
df = pd.DataFrame(trends[0]["trends"])

上記のコードを実行することで簡単に情報を取得できます。トレンドワードだけでなくそのタイムラインのURLやツイート数といった情報も併せて取得できます。

OAuthによる認証

Tweetを取得するsearchのAPIです。

# ライブラリのインポート
from requests_oauthlib import OAuth1Session
import pandas as pd
# Twitterデータ収集用のログインキーの情報
KEYS = { # 自分のアカウントで入手したキーを記載
        'consumer_key':'*************************',
        'consumer_secret':'**************************************************',
        'access_token':'**************************************************',
        'access_secret':'*********************************************',
       }

twitter = OAuth1Session(KEYS['consumer_key'],KEYS['consumer_secret'],KEYS['access_token'],KEYS['access_secret'])
def getTwitterData(key_word, repeat):
    url = "https://api.twitter.com/1.1/search/tweets.json"
    params ={'q': key_word, 'count':'100','lang':'ja', 'result_type':'recent'}
    tweets = []
    mid = -1
    break_flag = 0

    for i in range(repeat):
        params['max_id'] = mid
        res = twitter.get(url, params = params)
        if res.status_code == 200:
            sub_tweets = json.loads(res.text)['statuses']
            limit = res.headers['x-rate-limit-remaining'] if 'x-rate-limit-remaining' in res.headers else 0
#            print("API残接続可能回数:%s" % len(limit))            
            tweet_ids = []
            for tweet in sub_tweets:
                tweet_ids.append(int(tweet['id']))
                tweets.append(tweet)
            if len(tweet_ids) > 0:
                min_tweet_id = min(tweet_ids)
                mid = min_tweet_id - 1
            else:
                break_flag = 1
                break;

            ## 終了判定
            if break_flag == 1:
                break;

        else:
            print("Failed: %d" % res.status_code)
            break_flag = 1

    print("ツイート取得数:%s" % len(tweets))

    return tweets
tweets = getTwitterData("機械学習", 100)

ツイート取得数:4835(2022/2/5時点)

df_tweets = pd.DataFrame(tweets)
display(df_tweets.info())

スクリーンショット 2022-02-05 18.50.04.png

 最後に

今後はTwitterAPIから得られたデータをBigQueryに定期的に投入!!とかしたいですね。

 参考サイト

1, Analyze past conversations from Developer Platform
2, 学習データのラベル偏りに対する取り組み
3, YAHOO!リアルタイム検索
4, TwitterのAPIに登録し、アクセスキー・トークンを取得する具体的な方法
5, Response Codes
6, Tweepyの使い方
7, コールバックURLとは

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
1