5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

YouTube Live のリアルタイム視聴者数の取得方法

Last updated at Posted at 2021-06-08

YouTube Live のリアルタイム視聴者数の取得方法

はじめに

とあるYoutuberさんのラジオを聞いていたらチャンネル解析のためにLiveのリアルタイム視聴者の数を
定期的に目視確認していると仰っていたので、YouTubeAPIを使用したら自動化できるだろうなぁと思ったのがことの発端。
自動化することで本当にやりたいことができるのかは別。。。

元々Pythonは触ったことがある程度。。。
なにか不具合があったら教えて下さい。

リファレンス

以下URLの記事を参考にしました。
●YouTube APIキーの取得 (2020/03/25時点)
https://qiita.com/iroiro_bot/items/1016a6a439dfb8d21eca
●YouTube Live チャット欄をAPIでリアルタイム取得
https://qiita.com/iroiro_bot/items/ad0f3901a2336fe48e8f
●YouTube Data API v3でライブ配信の状態を取得する
https://coolish.hatenablog.com/

実行環境

M1 mac mini
python3はインストール済み

最初にやったこと

まずはYouTube APIキーの取得
以下参照
https://qiita.com/iroiro_bot/items/1016a6a439dfb8d21eca

以下ライブラリのインストール

$ pip3 install oauth2client
$ pip3 install httplib2
$ pip3 install isodate
$ pip3 install schedule
$ pip3 install csv

コード説明

1.以下コードの内「YT_API_KEY」の’’で囲まれた部分に上記で取得したAPIキーを記入する(’’は残しておく)
2.以下コード内の「YT_LIVE_URL」の’’でかこまれた部分に視聴者数を取得したいYoutube LiveのURLを貼り付ける(’’は残しておく)

コード

getCountViewers.py
import time
import datetime
import requests
import json
import schedule
import csv

YT_API_KEY = 'ここにYoutube API キーを貼り付け'
YT_LIVE_URL = '※※※ここに取得したいYouTube LiveのURLを貼り付け'
DP_FILE_NAME = './getLiveCountViewers.csv'

def get_currentViewers(yt_url):
    '''
    https://developers.google.com/youtube/v3/docs/videos/list?hl=ja
    '''
    videoId = yt_url.replace('https://www.youtube.com/watch?v=', '')
    #print('videoId : ', videoId)

    url    = 'https://www.googleapis.com/youtube/v3/videos'
    params = {'key': YT_API_KEY, 'id': videoId, 'part': 'liveStreamingDetails'}
    data   = requests.get(url, params=params).json()

    liveStreamingDetails = data['items'][0]['liveStreamingDetails']
    countViewers = liveStreamingDetails['concurrentViewers']

    dtNow = datetime.datetime.now()
    dumpTimes = dtNow.strftime('%Y/%m/%d %H:%M:%S')

    print(dumpTimes,",",countViewers)
    with open(DP_FILE_NAME, "a") as f:
        f.write("{0}, {1}\n".format(dumpTimes, countViewers))
        f.close()

def job():
    get_currentViewers(YT_LIVE_URL)

# test
# schedule.every(1).seconds.do(job) #テスト用1秒毎に取得
# schedule.every(1).minutes.do(job) #テスト用1分枚に取得
# 毎時00分に実行
schedule.every().hour.at(":00").do(job)

def main():
    while True:
        schedule.run_pending()
        time.sleep(1)

if __name__ == '__main__':
    main()

実行

上記ファイルをコピペで「getCountViewers.py」として保存する
ターミナルで以下コマンドを実行

$ python3 getCountViewers.py

出力

毎時00分にYouTubeLiveの視聴者数が「日時,視聴者数」で追加されていく
例:```
2021/06/09 04:00:00 , 42
2021/06/09 05:00:00 , 41
2021/06/09 06:00:00 , 42
2021/06/09 07:00:00 , 39


実行場所に以下ファイルが出力されるのでExcelで開いてグラフ化等で確認
```getLiveCountViewers.csv

注意事項

終了処理は書いていないので、終了したい場合は「CTRL-C」でお願いします。

備考

python導入方法

●MAC
https://prog-8.com/docs/python-env
●windows
https://prog-8.com/docs/python-env-win

Excelでグラフ化した際にうまく表示されない場合

http://www4.synapse.ne.jp/yone/excel2010/faq/graph_x.html
https://xtech.nikkei.com/atcl/nxt/column/18/00286/121200083/

最後に

読んで頂きありがとうございます。
初めてのQiita投稿で不安が一杯

5
5
1

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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?