Python + tweepyにて、Video URLを取得する

TwitterのVideo URLの取得方法を調べる機会がありましたので、メモとして残します。

なお、Twitter用ライブラリは、 tweepy を使います。

 
目次

 

環境

 

tweepyでTwitter APIを操作する

各種トークンを取得します。

auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)

 
tweepyにはCursorオブジェクトがあります。これを使うと、指定した数のツイートを取得できるため、ページングなどを気にする必要がないです。
Cursor Tutorial — tweepy 3.6.0 documentation

for status in tweepy.Cursor(api.user_timeline, 
    id='Twitter', since_id=560070183650213887,
    tweet_mode='extended').items(34):
        i += 1
print(i)

 
実行すると、

34

が出力されます。

 

ツイートとVideo URLが140文字に収まる場合

Video URLはどこに含まれているかを調べたところ、 extended_entities にあるようです。
Twitter REST APIを使って30秒動画の取得。$tweet->extended_entities->media[0]->video_info->variants[0]->url – エコテキブログ

以下のツイートで試してみます。
Twitterさんのツイート: "You can now shoot, edit and share video on Twitter. Capture life's most moving moments from your perspective. http://t.co/31JoMS50ha"

TWEET_ID = 560070183650213889
status = api.get_status(TWEET_ID)
print(status.text)
if hasattr(status, 'extended_entities'):
    for media in status.extended_entities.get('media', [{}]):
        if media.get('type', None) == 'video':
            print('video url: ' + media['video_info']['variants'][0]['url'])

実行結果です。

You can now shoot, edit and share video on Twitter. Capture life's most moving moments from your perspective. http://t.co/31JoMS50ha
video url: https://video.twimg.com/ext_tw_video/560070131976392705/pu/vid/640x360/vmLr5JlVs2kBLrXS.mp4

 

ツイートとVideo URLが140文字を超える場合

ツイートとVideo URLが140文字を超える場合は、少し動作が変わります。

別のツイート*1で実行してみると、

<長いツイート>やまな… https://t.co/xxx

みたいに、「…」でツイートが省略された上、extended_entitiesを取得できません。

 
この場合はどうするか調べたところ、APIを呼ぶ時に tweet_mode='extended' をつければ良さそうです。
Twitter Amplify Videos do not contain extended_entities · Issue #731 · tweepy/tweepy

 
また、 tweet_mode='extended'とした時は、 status.text がなくなり、 status.full_text になります。

# status = api.get_status(TWEET_ID)
# print(status.text)
status = api.get_status(TWEET_ID, tweet_mode='extended')
print(status.full_text)

 
実行してみます。

<長いツイート>やまない https://t.co/yyyy
video url: https://video.twimg.com/ext_tw_video/xxx.mp4

取得できました。また、短縮URLも先ほどのとは異なっていました。

 

【未解決】Videoが30秒より長い場合

こんな感じのツイートの場合、どう取得すればよいか不明です...
Twitter Videoさんのツイート: "Now, everyone can post videos up to 140 seconds long! We can’t wait to see the amazing videos you create and share. https://t.co/DFsuvnXkuL"

 

ソースコード

GitHubに上げました。 e.g._video_url ディレクトリの中身が今回のファイルです。
thinkAmi-sandbox/tweepy-sample thinkAmi-sandbox/tweepy-sample

*1:依頼された方のプライベートな感じなので、伏せ字にしておきます