LoginSignup
3
6

More than 1 year has passed since last update.

Twitter API で特定のユーザーのツイートを取得する(Python, tweepy)

Posted at

概要

tweepyというPythonのライブラリを用いて特定のユーザーのツイートを取得する。

目次

  • tweepy インストール
  • Client クラスの作成
  • ユーザーid の取得方法
  • ユーザーのツイートの取得

tweepy インストール

ターミナルで以下のコマンドを実行(anaconda)

pip install tweepy

Client クラスの作成

tweepyをインポートして、自身のAPI_keyなどを入れる。
Clientクラスのデフォルトのreturn_typeResponseとなっているので、必要に応じて、変更できる。詳しくは公式ドキュメント

import tweepy

API_key = "API_keyを入れてね"
API_key_Secret = "API key Secretを入れてね"
Access_Token = "Access Tokenを入れてね"
Access_Token_Secret = "Access Token Secretを入れてね"
Bearer_Token = "Bearer Tokenを入れてね"

client = tweepy.Client(
    Bearer_Token, API_key, API_key_Secret, 
    Access_Token, Access_Token_Secret,
    # return_type = dict
)
# default return type == Response
# Responseというクラスで返ってくるから必要な情報の取り方はTweepyドキュメントで確認
# type(...)で型の確認が可能

ユーザーid の取得方法

ユーザーidは、tweeteridというサイトで、TwitterIDを入れると見ることができる。今回は、例として@ twitter のユーザーidを取得した。

# @twitter
# idの取得は https://tweeterid.com/
user_id = 783214

ユーザーのツイートの取得

UsersTweetsにユーザーのツイートのResponseクラスを入れる。
UsersTweets.dataでツイートidとツイート内容が入ったlist形式のjsonファイルが得られる。

UsersTweets = client.get_users_tweets(user_id)

#Response クラスの中身は https://docs.tweepy.org/en/stable/response.html#tweepy.Response
for tweet in UsersTweets.data:
    print("===================")
    print("Tweet id:",tweet.id)
    print("Tweet text:", tweet.text)

出力結果

===================
Tweet id: 1540059169771978754
Tweet text: we would know
3
6
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
3
6