今回は Tweepy というライブラリを使って、日本一のフォロワー数を誇る前澤友作さんのツイートを取得してみたいと思います。
準備
事前準備として、
- Twitter API 認証情報の取得
- Tweepy のインストール
が必要です。
Twitter API 認証情報の取得
Twitter API を使用するための認証情報は Twitter の開発者向けサイトで申請して取得します。
通常の Twitter アカウントを使用して申請できます。
必要になる認証情報は次の4つです。
- API key
- API secret
- Access token
- Access secret(Access token secret)
4つともアルファベット大文字小文字、数字を組み合わせた、そこそこ長めの文字列になります。
Tweepy のインストール
Tweepy は pip でインストールします。
pip install tweepy
Google Colaboratory を使用する場合はデフォルトでインストールされていると思います。
Tweepy で前澤友作さんのツイートを取得してみる
準備ができたところで、早速、前澤友作さん(@yousuck2020)のツイートを取得してみましょう。
今回は次のようなコードを書きました。
4つの認証情報の文字列はご自身で取得されたものに書き換えてください。
import tweepy
API_KEY = "ApiKeyDayo123ApiKeyDayo456"
API_SECRET_KEY = "ApiSecretDayo123ApiSecretDayo456"
ACCESS_TOKEN = "aCcessTokenDayo987aCcessTokenDayo654"
ACCESS_TOKEN_SECRET = "accEssSecretDayo321accEssSecretDayo789"
def twitter_api() -> tweepy.API:
auth = tweepy.OAuthHandler(API_KEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
return tweepy.API(auth)
def get_user_timeline(user_id):
api = twitter_api()
tweets = api.user_timeline(id=user_id, count=3)
for tweet in tweets:
print("=============================")
print(tweet.text)
get_user_timeline('yousuck2020')
本記事を書いている時点で上記コードを実行すると、次のような結果を得ることができました。
=============================
RT @sosotakei: 今週は前澤さんと保護猫、保護犬を大切に育ててくださる方々へ、また飼いたいけど資金が、と言う方にもご応募いただけます
命を大切にしてくれるみなさんのご応募お待ちしてます
ワンちゃんネコちゃんの幸せの一部に使ってくださいね(๑˃̵ᴗ˂̵) https:…
=============================
今週のコラボ協力支援者は、武井壮さん @sosotakei です。
武井さんからのコメントや、今後の予定はこちら↓をご覧ください。
https://t.co/fEEwK89kzy
また、武井さんのようにコラボしていただける協力支援者も個人・法人問わず募集中です!
=============================
今週は【保護犬保護猫を飼われている方、またはこれからお迎えしたい方】を対象に、200名様に5万円の支援金を贈ります。
ご応募は↓こちらから
https://t.co/0mefMZAB83
解説
今回は Tweepy の user_timeline()
メソッドを使いました。
タイムラインなので、リツイートも含まれています。
user_timeline()
メソッドの引数としてid
とcount
を指定しました。
id
はTwitterの@から始まるユーザー名です。@は不要です。
count
は取得するツイートの件数を入れます。
今回は最新3件を取得しました。
count
を指定しないと、最新20件が取得できるようです。
user_timeline()
メソッドについては、公式のドキュメントもあるので、こちらも確認してみてください。
user_timeline()
メソッドの返り値は「Status
オブジェクト」という形式になっています。
1件だけ、このStatus
オブジェクトのまま取得してみると、次のようなデータが得られます。
Status(_api=<tweepy.api.API object at 0x102ec1f10>, _json={'created_at': 'Mon Mar 29 07:54:55 +0000 2021', 'id': 1376442732617506817, 'id_str': '1376442732617506817', 'text': '今週は【保護犬保護猫を飼われている方、またはこれからお迎えしたい方】を対象に、200名様に5万円の支援金を贈ります。\n\nご応募は↓こちらから\nhttps://t.co/0mefMZAB83', 'truncated': False, 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/0mefMZAB83', 'expanded_url': 'https://donation.yusakumaezawa.com/contact08/index.html', 'display_url': 'donation.yusakumaezawa.com/contact08/inde…', 'indices': [71, 94]}]}, 'source': '<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'user': {'id': 137857547, 'id_str': '137857547', 'name': '前澤友作┃お金贈りおじさん', 'screen_name': 'yousuck2020', 'location': '', 'description': 'English account → @yousuckMZ 年内にフォロワー全員にお金贈り→https://t.co/hePnvpRGDW Instagram → https://t.co/8WRxNUBMkj', 'url': 'https://t.co/wsRJKYNnDy', 'entities': {'url': {'urls': [{'url': 'https://t.co/wsRJKYNnDy', 'expanded_url': 'https://www.youtube.com/c/YusakuMaezawaTV', 'display_url': 'youtube.com/c/YusakuMaezaw…', 'indices': [0, 23]}]}, 'description': {'urls': [{'url': 'https://t.co/hePnvpRGDW', 'expanded_url': 'https://donation.yusakumaezawa.com/', 'display_url': 'donation.yusakumaezawa.com', 'indices': [45, 68]}, {'url': 'https://t.co/8WRxNUBMkj', 'expanded_url': 'https://www.instagram.com/yusaku2020/', 'display_url': 'instagram.com/yusaku2020/', 'indices': [81, 104]}]}}, 'protected': False, 'followers_count': 11086105, 'friends_count': 102, 'listed_count': 7044, 'created_at': 'Tue Apr 27 23:59:08 +0000 2010', 'favourites_count': 185, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 5950, 'lang': None, 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'C0DEED', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/137857547/1609464333', 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': True, 'default_profile': True, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': True, 'translator_type': 'none'}, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 11372, 'favorite_count': 31931, 'favorited': False, 'retweeted': False, 'possibly_sensitive': False, 'lang': 'ja'}, created_at=datetime.datetime(2021, 3, 29, 7, 54, 55), id=1376442732617506817, id_str='1376442732617506817', text='今週は【保護犬保護猫を飼われている方、またはこれからお迎えしたい方】を対象に、200名様に5万円の支援金を贈ります。\n\nご応募は↓こちらから\nhttps://t.co/0mefMZAB83', truncated=False, entities={'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/0mefMZAB83', 'expanded_url': 'https://donation.yusakumaezawa.com/contact08/index.html', 'display_url': 'donation.yusakumaezawa.com/contact08/inde…', 'indices': [71, 94]}]}, source='Twitter for iPhone', source_url='http://twitter.com/download/iphone', in_reply_to_status_id=None, in_reply_to_status_id_str=None, in_reply_to_user_id=None, in_reply_to_user_id_str=None, in_reply_to_screen_name=None, author=User(_api=<tweepy.api.API object at 0x102ec1f10>, _json={'id': 137857547, 'id_str': '137857547', 'name': '前澤友作┃お金贈りおじさん', 'screen_name': 'yousuck2020', 'location': '', 'description': 'English account → @yousuckMZ 年内にフォロワー全員にお金贈り→https://t.co/hePnvpRGDW Instagram → https://t.co/8WRxNUBMkj', 'url': 'https://t.co/wsRJKYNnDy', 'entities': {'url': {'urls': [{'url': 'https://t.co/wsRJKYNnDy', 'expanded_url': 'https://www.youtube.com/c/YusakuMaezawaTV', 'display_url': 'youtube.com/c/YusakuMaezaw…', 'indices': [0, 23]}]}, 'description': {'urls': [{'url': 'https://t.co/hePnvpRGDW', 'expanded_url': 'https://donation.yusakumaezawa.com/', 'display_url': 'donation.yusakumaezawa.com', 'indices': [45, 68]}, {'url': 'https://t.co/8WRxNUBMkj', 'expanded_url': 'https://www.instagram.com/yusaku2020/', 'display_url': 'instagram.com/yusaku2020/', 'indices': [81, 104]}]}}, 'protected': False, 'followers_count': 11086105, 'friends_count': 102, 'listed_count': 7044, 'created_at': 'Tue Apr 27 23:59:08 +0000 2010', 'favourites_count': 185, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 5950, 'lang': None, 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'C0DEED', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/137857547/1609464333', 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': True, 'default_profile': True, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': True, 'translator_type': 'none'}, id=137857547, id_str='137857547', name='前澤友作┃お金贈りおじさん', screen_name='yousuck2020', location='', description='English account → @yousuckMZ 年内にフォロワー全員にお金贈り→https://t.co/hePnvpRGDW Instagram → https://t.co/8WRxNUBMkj', url='https://t.co/wsRJKYNnDy', entities={'url': {'urls': [{'url': 'https://t.co/wsRJKYNnDy', 'expanded_url': 'https://www.youtube.com/c/YusakuMaezawaTV', 'display_url': 'youtube.com/c/YusakuMaezaw…', 'indices': [0, 23]}]}, 'description': {'urls': [{'url': 'https://t.co/hePnvpRGDW', 'expanded_url': 'https://donation.yusakumaezawa.com/', 'display_url': 'donation.yusakumaezawa.com', 'indices': [45, 68]}, {'url': 'https://t.co/8WRxNUBMkj', 'expanded_url': 'https://www.instagram.com/yusaku2020/', 'display_url': 'instagram.com/yusaku2020/', 'indices': [81, 104]}]}}, protected=False, followers_count=11086105, friends_count=102, listed_count=7044, created_at=datetime.datetime(2010, 4, 27, 23, 59, 8), favourites_count=185, utc_offset=None, time_zone=None, geo_enabled=False, verified=True, statuses_count=5950, lang=None, contributors_enabled=False, is_translator=False, is_translation_enabled=False, profile_background_color='C0DEED', profile_background_image_url='http://abs.twimg.com/images/themes/theme1/bg.png', profile_background_image_url_https='https://abs.twimg.com/images/themes/theme1/bg.png', profile_background_tile=False, profile_image_url='http://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', profile_image_url_https='https://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', profile_banner_url='https://pbs.twimg.com/profile_banners/137857547/1609464333', profile_link_color='1DA1F2', profile_sidebar_border_color='C0DEED', profile_sidebar_fill_color='DDEEF6', profile_text_color='333333', profile_use_background_image=True, has_extended_profile=True, default_profile=True, default_profile_image=False, following=True, follow_request_sent=False, notifications=True, translator_type='none'), user=User(_api=<tweepy.api.API object at 0x102ec1f10>, _json={'id': 137857547, 'id_str': '137857547', 'name': '前澤友作┃お金贈りおじさん', 'screen_name': 'yousuck2020', 'location': '', 'description': 'English account → @yousuckMZ 年内にフォロワー全員にお金贈り→https://t.co/hePnvpRGDW Instagram → https://t.co/8WRxNUBMkj', 'url': 'https://t.co/wsRJKYNnDy', 'entities': {'url': {'urls': [{'url': 'https://t.co/wsRJKYNnDy', 'expanded_url': 'https://www.youtube.com/c/YusakuMaezawaTV', 'display_url': 'youtube.com/c/YusakuMaezaw…', 'indices': [0, 23]}]}, 'description': {'urls': [{'url': 'https://t.co/hePnvpRGDW', 'expanded_url': 'https://donation.yusakumaezawa.com/', 'display_url': 'donation.yusakumaezawa.com', 'indices': [45, 68]}, {'url': 'https://t.co/8WRxNUBMkj', 'expanded_url': 'https://www.instagram.com/yusaku2020/', 'display_url': 'instagram.com/yusaku2020/', 'indices': [81, 104]}]}}, 'protected': False, 'followers_count': 11086105, 'friends_count': 102, 'listed_count': 7044, 'created_at': 'Tue Apr 27 23:59:08 +0000 2010', 'favourites_count': 185, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': True, 'statuses_count': 5950, 'lang': None, 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'C0DEED', 'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png', 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/137857547/1609464333', 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': True, 'default_profile': True, 'default_profile_image': False, 'following': True, 'follow_request_sent': False, 'notifications': True, 'translator_type': 'none'}, id=137857547, id_str='137857547', name='前澤友作┃お金贈りおじさん', screen_name='yousuck2020', location='', description='English account → @yousuckMZ 年内にフォロワー全員にお金贈り→https://t.co/hePnvpRGDW Instagram → https://t.co/8WRxNUBMkj', url='https://t.co/wsRJKYNnDy', entities={'url': {'urls': [{'url': 'https://t.co/wsRJKYNnDy', 'expanded_url': 'https://www.youtube.com/c/YusakuMaezawaTV', 'display_url': 'youtube.com/c/YusakuMaezaw…', 'indices': [0, 23]}]}, 'description': {'urls': [{'url': 'https://t.co/hePnvpRGDW', 'expanded_url': 'https://donation.yusakumaezawa.com/', 'display_url': 'donation.yusakumaezawa.com', 'indices': [45, 68]}, {'url': 'https://t.co/8WRxNUBMkj', 'expanded_url': 'https://www.instagram.com/yusaku2020/', 'display_url': 'instagram.com/yusaku2020/', 'indices': [81, 104]}]}}, protected=False, followers_count=11086105, friends_count=102, listed_count=7044, created_at=datetime.datetime(2010, 4, 27, 23, 59, 8), favourites_count=185, utc_offset=None, time_zone=None, geo_enabled=False, verified=True, statuses_count=5950, lang=None, contributors_enabled=False, is_translator=False, is_translation_enabled=False, profile_background_color='C0DEED', profile_background_image_url='http://abs.twimg.com/images/themes/theme1/bg.png', profile_background_image_url_https='https://abs.twimg.com/images/themes/theme1/bg.png', profile_background_tile=False, profile_image_url='http://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', profile_image_url_https='https://pbs.twimg.com/profile_images/1065419302256275456/y1oe1dOQ_normal.jpg', profile_banner_url='https://pbs.twimg.com/profile_banners/137857547/1609464333', profile_link_color='1DA1F2', profile_sidebar_border_color='C0DEED', profile_sidebar_fill_color='DDEEF6', profile_text_color='333333', profile_use_background_image=True, has_extended_profile=True, default_profile=True, default_profile_image=False, following=True, follow_request_sent=False, notifications=True, translator_type='none'), geo=None, coordinates=None, place=None, contributors=None, is_quote_status=False, retweet_count=11372, favorite_count=31931, favorited=False, retweeted=False, possibly_sensitive=False, lang='ja')
※ 1行のかなり長い文字列になっています。
今回はこの中のtext
という項目をtweet.text
という形で抜き出して、出力しています。
全部は確認していませんが、Status
オブジェクトの中にはハッシュタグやリンクが貼られているURL、いいねの数などの情報も含まれているようです。
Google Colaboratory
今回のコードは Google Colaboratory での動作を確認しています。
環境構築の不要な Google が提供している Webサービスなので、Python を学習中の方にはオススメです。
おわりに
今回は Tweepy というライブラリを使って、前澤友作さんのツイートを取得してみました。
Tweepy を使うと、めちゃくちゃ簡単に Twiiter API を利用することができるので、ぜひ一度使ってみてはいかがでしょうか?
Google Colaboratory でも動かすことができ、簡単に試すことができるので、オススメです。
以上です。
コメント