LoginSignup
11
18

More than 5 years have passed since last update.

pythonでツイッターのタイムラインの取得

Last updated at Posted at 2017-01-19

1. はじめに

普段からtwitterを使うためプログラムを用いて投稿やタイムラインの取得を行いたいので、
それを行うための備忘録としてここに残します。

ここでは以下の内容を記載します。
イ. タイムラインの取得
ロ. ツイートに含まれる情報を見るには

また環境等はpythonでツイートの投稿と同様であり、API keyを取得していることが前提となります。

2. タイムラインの取得

タイムラインの取得をするには次のようなURLが必要であり、
パラメータを変更することで取得できるタイムラインが変わります。

twitter_access.py
url = "https://api.twitter.com/1.1/statuses/home_timeline.json"
params = {"count":200, #ツイートを最新から何件取得するか(最大200件)
          "include_entities" : 1, #エンティティ(画像のURL等)をツイートに含めるか
          "exclude_replies" : 1, #リプライを含めるか
          }

req = sess.get(url, params=params)
timeline = json.loads(req.text)

こうすることによりtimelineという名前のリストに辞書型でツイートが代入されます。

一つ一つツイートを見ていきたい場合にはfor文等で回しましょう。

twitter_access.py
for tweet in timeline:
    print(tweet["text"])

3. ツイートに含まれる情報を見るには

辞書型のツイートには次のようなキーがあります。

'is_quote_status', 'in_reply_to_user_id_str', 'place', 'geo', 'retweet_count', 'id_str', 'id', 'contributors', 'user', 'retweeted', 'text', 'in_reply_to_user_id', 'lang', 'in_reply_to_screen_name', 'truncated', 'source', 'favorite_count', 'created_at', 'entities', 'favorited', 'in_reply_to_status_id_str', 'coordinates', 'in_reply_to_status_id'

このキーで様々な要素を取得できます。
例として'text'を使えばツイートの本文を文字列として取得できます。
userにはツイートしたユーザーの情報が辞書型で格納されています

userのキーは以下の通りです。

'url', 'profile_background_tile', 'screen_name', 'profile_image_url', 'following', 'has_extended_profile', 'statuses_count', 'profile_background_color', 'profile_sidebar_fill_color', 'contributors_enabled', 'notifications', 'listed_count', 'translator_type', 'id', 'profile_background_image_url', 'profile_image_url_https', 'profile_link_color', 'profile_background_image_url_https', 'favourites_count', 'profile_banner_url', 'friends_count', 'location', 'default_profile_image', 'lang', 'verified', 'follow_request_sent', 'profile_use_background_image', 'profile_text_color', 'geo_enabled', 'protected', 'followers_count', 'description', 'is_translator', 'id_str', 'created_at', 'name', 'entities', 'time_zone', 'profile_sidebar_border_color', 'is_translation_enabled', 'utc_offset', 'default_profile'

また、たまにツイートのキーにextended_entitiesというキーがある場合があります。
このキーの中にはまた辞書型が格納されており、mediaというキーの中にさらにmedia_urlというキーがあります。
この中にツイートに付随している画像のURLがあります。

次はたぶんないです。

11
18
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
11
18