Twitter API で特定のハッシュタグを含む最近のツイートを取得してCSVに出力する
これは何?
TwitterのAPIを使って、特定のハッシュタグを含む最近の(下記のコード例では直近10000件の)ツイートを取得し、CSVファイルに(下記の例では本文と投稿日時を)出力する方法。予めTwitter APIの利用申請をして、コンシューマーキー〜アクセストークンシークレットまでを取得しておくこと。
実行方法
code:sh
pip install requests_oauthlib # ライブラリのインストール
python main.py # ファイルの実行(実行できる場所で叩く)
cat result.csv # ファイルの中身を表示(実際はコンソールではみないが)
プログラム例
code:main.py
import urllib
from requests_oauthlib import OAuth1
import requests
import sys
import csv
def main():
# APIの秘密鍵
CK = 'xx' # コンシューマーキー
CKS = 'xx' # コンシューマーシークレット
AT = 'xx' # アクセストークン
ATS = 'xx' # アクセストークンシークレット
# 検索時のパラメーター
word = '(#BlackLivesMatter)' # 検索ワード ※ ()に囲むとハッシュタグ検索になる
count = 100 # 一回あたりの検索数(最大100/デフォルトは15)
range = 100 # 検索回数の上限値(最大180/15分でリセット)
# ツイート検索・テキストの抽出
tweets = search_tweets(CK, CKS, AT, ATS, word, count, range)
# 検索結果を表示
print(tweets0:4)
with open("./result.csv", "w", newline="") as f:
writer.writerow("full_text", "created_a", "retweet_count", "favorite_count", "url")
writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_ALL)
for tweet in tweets:
writer.writerow(tweet)
def search_tweets(CK, CKS, AT, ATS, word, count, range):
# 文字列設定
word += ' exclude:retweets' # RTは除く
word = urllib.parse.quote_plus(word)
# リクエスト
url = "https://api.twitter.com/1.1/search/tweets.json?lang=ja&trim_user=true&tweet_mode=extended&q="+word+"&count="+str(count)
auth = OAuth1(CK, CKS, AT, ATS)
response = requests.get(url, auth=auth)
data = response.json()'statuses'
print(data0)
# 2回目以降のリクエスト
cnt = 0
tweets = []
while True:
if len(data) == 0:
break
cnt += 1
if cnt > range:
break
for tweet in data:
tweets.append([tweet'full_text', tweet'created_at', tweet'retweet_count', tweet'favorite_count', "https://twitter.com/i/web/status/" + tweet'id_str'])
maxid = int(tweet"id") - 1
print(maxid)
url = "https://api.twitter.com/1.1/search/tweets.json?lang=ja&trim_user=true&tweet_mode=extended&q="+word+"&count="+str(count)+"&max_id="+str(maxid)
response = requests.get(url, auth=auth)
try:
data = response.json()'statuses'
except KeyError: # リクエスト回数が上限に達した場合のデータのエラー処理
print('上限まで検索しました')
break
return tweets
if __name__ == '__main__':
main()
参考
ベースにしたコード
CSVライブラリの仕様
CSVライブラリの使い方
Twitter APIにおけるツイート全文の取得方法