今回はYoutube Data APIを使ってPythonでYoutubeの生放送(Live放送)の同時視聴者数(同接数)をスクレイピングしたいと思います。
Youtubeライブの同接数をPythonでのスクレイピングで取得する
基本的には通常の投稿動画の再生回数を取得する時と変わらないのですが、生放送の動画の場合はAPIを叩いた際の戻り値に[‘liveStreamingDetails’]という項目があり、ここで同時接続者数が確認できます。
import requests
import datetime
import json
from apiclient.discovery import build
YOUTUBE_API_KEY = 'xxxxxxxxxxxxxxxxxxxx'
youtube = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
# チャンネルURLから同接数を調べて返す関数
def get_currentViewers(yt_url):
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()
#print(data)
liveStreamingDetails = data['items'][0]['liveStreamingDetails']
try:
countViewers = liveStreamingDetails['concurrentViewers']
except:
countViewers = 0
dtNow = datetime.datetime.now()
dumpTimes = dtNow.strftime('%Y/%m/%d %H:%M:%S')
print(dumpTimes,",",countViewers)
return [dumpTimes,countViewers]
# 生放送中の動画のURL
live_url = 'https://www.youtube.com/watch?v=xxxxx'
# 関数の実行
get_currentViewers(live_url)
Youtubeライブ配信動画をキーワード検索する
こちらも通常の動画検索APIと共用なのですが、注意するべきは引数の設定でライブを検索するeventType='live'を使用する際はtype='video'も一緒に設定しておかないとパラメーターエラーになります。
# 現在のライブ情報を取得
q='にじさんじ'
search_response = youtube.search().list(
part='snippet',
q=q,
order='viewCount',
# regionCode='JP',
maxResults=50,
type='video',
eventType='live',
).execute()
for item in search_response['items']:
channel_id = item['snippet']['channelId']
live_title = item['snippet']['title']
live_id = item['id']['videoId']
print(live_title, channel_id , live_id )
get_currentViewers(live_id)
print('---------------------------------')
<実行結果>

関連記事
・【Python】Youtube Data APIを使ってYoutubeチャンネルの
・【Python】Youtubeの再生数・コメント数・高評価数をスクレイピングで取得する
・【Python】Youtubeの動画コメントをAPIで全件取得してCSVに保存する
・【Python】YoutubeのAPIを叩いて検索結果と各動画の再生回数を取得する

コメント