(Python)tweepyを使用してTweetの取得

(Python)tweepyを使用してTweetの取得

はじめに


参考にした公式ドキュメントです。
詳しく知りたいかたはこちらへどうぞ。
https://kurozumi.github.io/tweepy/api.html

tweepy使い方

tweepyを使うと特定のツイッターさんのツイートを取得したり、キーワード検索でツイート取得することができます。

そのやり方をお教えします。

install

インストールが未だの方は pip install しましょう。

pip install tweepy

初期設定

import と APIKeyの設定を行います。

import tweepy

APIKEY = '*************************'
API_SECRET_KEY = '*************************'
ACCESS_TOKEN = '*************************'
ACCESS_TOKEN_SECRET = '*************************'

auth = tweepy.OAuthHandler(APIKEY, API_SECRET_KEY)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

取得方法(timeline)

home_timeline


フォロワーのretweetsを含む最新のツイートを返します
web上のhttps://twitter.com/homeに相当します。

timelines = api.home_timeline() # defaultで20個取得
timelines = api.home_timeline(count=200) # 最大200まで取得可能
timelines = api.home_timeline(count=400) # 200個の取得(1~200の範囲で指定する)

# 200個以上取得したい場合(600個の取得)
count = 200
page = 3
for i in range(1, page+1):
    timelines = api.home_timeline(count=count, page=i)

user_timeline

ユーザー指定してツイートを取得できます。


@以降のnameでの取得可能です。@は付いてても付いていなくても問題ないです。
id と screen_name はどちらでも同じように取得できるみたいです。

id_name = screen_name = 'dairy_english_1'

timelines = api.user_timeline(id=id_name) # default 20件取得
timelines = api.user_timeline(screen_name=screen_name) # default 20件取得

timelines = api.user_timeline(id=id_name, count=200) # 取得件数指定 200件取得
timelines = api.user_timeline(id=id_name, include_rts=False) # Flaseならリツイートを除外する
timelines = api.user_timeline(id=id_name, exclude_replies=True) # Trueならリプライを除外する

# 件数指定, リツイート・リプライ除外
timelines = api.user_timeline(
    id=id_name,
    count=200,
    include_rts=False,
    exclude_replies=True)

取得可能な分だけ取得する

指定したユーザーのツイートを取得可能な分だけ取得します。
取得ができなくなるとlen(timelines) が0になり、while文を抜けます。

id_name = 'dairy_english_1'
timelines = api.user_timeline(id=id_name, count=1)

max_id = timelines[0].id
count = 200

tweets = []
while 0 < len(timelines):
    timelines = api.user_timeline(
        count=count,
        id=id_name,
        max_id = max_id)
    tweets.extend(timeline) # 配列にtimelineを追加
    max_id = tweets[-1].id -1

max_idを指定することで、そのツイートを含む過去のツイートが取得できます。

レスポンスから値を取得する

ここでレスポンスから取得する値は、
TwitterID, ツイート内容, リツイート数, いいね数,
ツイート時間, 一般的なアカウント名, @後のユーザー名, URLです。

timelines = api.user_timeline(id=id_name)

for tweet in timelines:
    tweet_id = tweet.id # TwitterID
    text = tweet.text # ツイート本文
    retweet_count = tweet.retweet_count # リツイート数
    favorite_count = tweet.favorite_count # いいね数
    created_at = (tweet.created_at + timedelta(hours=9)).strftime('%Y/%m/%d %H:%M:%S') # ツイート時間
    name = tweet.user.name # 一般的なアカウント名
    screen_name = tweet.user.screen_name # @後のユーザー名
    url = 'https://twitter.com/' + screen_name + '/status/' + str(tweet_id) # URL
    
    print(tweet_id)
    print(text)
    print(retweet_count)
    print(favorite_count)
    print(created_at)
    print(name)
    print(screen_name)
    print(url)

140文字以上のツイートを取得する場合


デフォルトでは141文字以上に対応していないみたいです。
取得時に tweet_mode='extended' を追加することで取得が可能になります。

レスポンスの形式が少し変わるのでツイート本文の取り出しには full_textを使用します。
それ以外は同じ取得方法で大丈夫なはずです。

id_name = 'dairy_english_1'
timelines = api.user_timeline(id=id_name, tweet_mode='extended')

for tweet in timelines:
    text = tweet.full_text # ツイート本文

全体コード


実際にPythonでtweepyを動かしてみましょう。
ツイートを取得して内容をコンソールに表示するコードです。

import tweepy
from datetime import timedelta

APIKEY = '*************************'
API_SECRET_KEY = '*************************'
ACCESS_TOKEN = '*************************'
ACCESS_TOKEN_SECRET = '*************************'

# 取得したいTwiiterName
ID_NAME = 'dairy_english_1'

def main():
    
    auth = tweepy.OAuthHandler(APIKEY, API_SECRET_KEY)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
    
    timelines = api.user_timeline(id=ID_NAME, count=1, tweet_mode='extended')
    max_id = timelines[0].id
    count = 200
    
    tweets = []
    
#     tweets.extend(timelines) # お試し時用
#     while False: # お試し時はFalseにして、上のtimelinesの取得でcount=10を設定する
    while 0 < len(timelines):
        timelines = api.user_timeline(
            count=count,
            id=ID_NAME,
            max_id = max_id,
            tweet_mode='extended')
        tweets.extend(timelines)
        max_id = tweets[-1].id -1
    
    print(tweets[0].user.name)
    for tweet in tweets:
        text = (tweet.created_at + timedelta(hours=9)).strftime("%Y/%m/%d %H:%M:%S")
        text += '\n\n' + tweet.full_text
        text += '\n\nリツイート: ' + str(tweet.retweet_count)
        text += ', いいね:' + str(tweet.favorite_count)
        text += '\nhttps://twitter.com/' + tweet.user.screen_name + '/status/' + str(tweet.user.id)
        text += '\n------------------------------------'
        print(text)
            
if __name__ == '__main__':
    print('始')
    main()
    print('終')

レート制限を超えたエラー時の対処方法

TweepError: [{‘message’: ‘Rate limit exceeded’, ‘code’: 88}]

レート制限を超えた場合に出るエラーみたいです。

いつ回復するのか知りたい方はapi設定時に
wait_on_rate_limit と wait_on_rate_limit_notifyの設定を追加します。

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

設定を追加してあげるとエラーではなく、

Rate limit reached. Sleeping for: 260

と表示されスリープ中と出力されるようになりました。
単位は秒です。
今回のでいえば260秒ですね。

あとは放置していたら無事動いてくれました。

以上、Twitterからツイートを取得方法でした。

programmingカテゴリの最新記事