もちブログ

とある技術職会社員の雑記

Twitter Premium Search APIを使ってツイートを集めた

f:id:mochi1103blog:20191106212053j:plain

はじめに

大学の研究で機械学習を用いて文章生成を行うために、大量のテキストデータが欲しかったのでそのコーパスとしてツイートを集めました。
Developerアカウントの作成後ツイート取得まで、色々手こずったので備忘録として書いておきます。

Twitter API

Twitter APIにはSandbox、Premium、Enterpriseの3種類があり、それぞれ使える機能も異なります。詳細については割愛します。
今回はPremiumのFull-Archiveを利用しました。

Search API Full-Archive

Full-Archiveは2004年以降のツイート全てが取得できます。
一度のリクエストで500ツイートまで取得でき、さらに1ヶ月あたりに最高で2500リクエストできるので最大で125万ツイート収集することができます。
今回は科研費の都合上、500リクエスト/月できるものを利用しました。

アカウント作成

Developerアカウントを持っていない場合はApply for access – Twitter Developersからアカウントを作成してください。

認証キー取得

アカウント作成後、DeveloperアカウントのDashboardの右上ドロップダウン「Apps」→「Create an app」
アプリ名や概要を入力します。requiredと書かれている項目は必須項目なので必ず全て埋めてください。
入力後「Create」→ 作成したアプリの「Detail」→「Keys and tokens」よりConsumer KeyとAccess tokenを確認し、控えておいてください。

認証キーファイル作成

取得した認証キーをあらかじめ1つのファイルにまとめておく必要があるので、ファイルを作成します。

account_typeは利用するAPIを選択するので「premium」を指定してください
endpointは検索に利用するエンドポイントを記述します。
consumer_keyとconsumer_seccretは前項にて取得したキーを入力してください。

ツイート取得

認証キーを保存したファイルを用意したのであとはソースを書いてツイートを取得するだけです。

# -*- coding: utf-8 -*-
from requests_oauthlib import OAuth1Session
from searchtweets import ResultStream, gen_rule_payload, load_credentials
from searchtweets import collect_results

#--------------------
# Authentication
#--------------------
#Authenticate Premium Search API
premium_search_args = load_credentials("./twitter_keys.yaml",
                                        yaml_key="search_tweets_api",
                                        env_overwrite=False)

#検索条件指定
#この場合だと「beyonce」について検索、という条件
rule = gen_rule_payload("beyonce", results_per_call=500)

#Premium APIを使って「beyonce」について検索、検索結果のツイートを取得
rs = ResultStream(rule_payload=rule,max_results=1000,**premium_search_args)

#取得結果をリスト化
tweets = list(rs.stream())

#取得結果出力
[print(tweet.all_text, end='\n\n') for tweet in tweets[0:10]];

取得例

Jay-Z & Beyoncé sat across from us at dinner tonight and, at one point, I made eye contact with Beyoncé. My limbs turned to jello and I can no longer form a coherent sentence. I have seen the eyes of the lord.

Beyoncé and it isn't close. https://t.co/UdOU9oUtuW

As you could guess.. Signs by Beyoncé will always be my shit.

When Beyoncé adopts a dog 🙌🏾 https://t.co/U571HyLG4F

Hold up, you can't just do that to Beyoncé
https://t.co/3p14DocGqA

Why y'all keep using Rihanna and Beyoncé gifs to promote the show when y'all let Bey lose the same award she deserved 3 times and let Rihanna leave with nothing but the clothes on her back? https://t.co/w38QpH0wma

30) anybody tell you that you look like Beyoncé https://t.co/Vo4Z7bfSCi

Mi Beyoncé favorita https://t.co/f9Jp600l2B
Beyoncé necesita ver esto. Que diosa @TiniStoessel 🔥🔥🔥 https://t.co/gadVJbehQZ

Joanne Pearce Is now playing IF I WAS A BOY - BEYONCE.mp3 by !

I'm trynna see beyoncé's finsta before I die