2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

好きなYouTuberの一番再生された動画をPythonで取得してみた

2
Posted at

必要なもの

・YouTubeのAPIキー
・取得したいチャンネルID
・Python実行環境

APIキー取得

まずはYouTubeのAPIキーを取得するところから (無料)

APIキーとは
Google Cloud Platform(GCP)が発行する認証用の文字列です。
これがないとAPIにアクセスできません。

APIキーの取得手順

・Google Cloud Console にアクセス (https://console.cloud.google.com/)
・プロジェクトを作成(または既存プロジェクトを選択)
・左メニューから「APIとサービス」→「ライブラリ」を開く
・「YouTube Data API v3」を検索して有効にする
・左メニューから「認証情報」→「認証情報を作成」→「APIキー」を選択
・発行されたAPIキーが表示されるのでコピー
・以下Pythonコード記載のAPI_KEY = "YOUR_API_KEY"を自身のに置き換える

API_KEY = "AIzaSyDXXXXXX-XXXXXXXXXX-XXXXXXXXXX"

こんな感じのKeyだったらOK
絶対外部に漏れないように:no_entry_sign:

APIライブラリのインポート

Google公式のPython用APIクライアントライブラリを使って
YouTube Data API v3 にアクセスするためのインポート

ライブラリが入ってない場合は先に入れておく

pip install google-api-python-client

Pythonコード

#!/usr/bin/env python3
from googleapiclient.discovery import build

API_KEY = "YOUR_API_KEY"  # ここに自身のAPIキーを貼り付け
HANDLE  = "@HikakinTV"    # ハンドル名(@付き) ここではHIKAKINTVで固定

youtube = build("youtube", "v3", developerKey=API_KEY)

def get_channel_id_by_handle(handle):
    # ハンドル名からチャンネルIDを検索
    response = youtube.search().list(
        part = "snippet",
        q    = handle,
        type = "channel",
        maxResults = 1
    ).execute()

    items = response.get("items", [])
    if not items:
        return None
    return items[0]["snippet"]["channelId"]

def get_most_viewed_video(channel_id):
    channel_res = youtube.channels().list(
        part = "contentDetails",
        id   = channel_id
    ).execute()
    uploads_playlist_id = channel_res["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]

    videos = []
    next_page_token = None

    while True:
        playlist_res = youtube.playlistItems().list(
            part       = "contentDetails",
            playlistId = uploads_playlist_id,
            maxResults = 50,
            pageToken  = next_page_token
        ).execute()

        for item in playlist_res["items"]:
            videos.append(item["contentDetails"]["videoId"])

        next_page_token = playlist_res.get("nextPageToken")
        if not next_page_token:
            break

    most_viewed   = None
    highest_views = -1

    for i in range(0, len(videos), 50):
        video_ids = videos[i:i+50]
        stats_res = youtube.videos().list(
            part = "statistics,snippet",
            id   = ",".join(video_ids)
        ).execute()

        for item in stats_res["items"]:
            statistics     = item.get("statistics", {})
            view_count_str = statistics.get("viewCount")
            if view_count_str is None:
                continue
            view_count = int(view_count_str)
            if view_count > highest_views:
                highest_views = view_count
                most_viewed   = {
                    "title"  : item["snippet"]["title"],
                    "videoId": item["id"],
                    "views"  : view_count
                }

    return most_viewed

if __name__ == "__main__":
    channel_id = get_channel_id_by_handle(HANDLE)
    if channel_id is None:
        print(f"ハンドル {HANDLE} に該当するチャンネルが見つかりませんでした。")
    else:
        print(f"チャンネルID: {channel_id}")
        result = get_most_viewed_video(channel_id)
        if result:
            print(f"最も再生された動画: {result['title']} ({result['views']} 回再生)")
            print(f"URL: https://www.youtube.com/watch?v={result['videoId']}")
        else:
            print("動画が見つかりませんでした。")

複数のハンドル名をループすれば、複数チャンネルのトップ動画を確認できる
色んな用途に展開できそう:film_frames:(もっとシンプルに書ける気がする)

実行結果

(venv) root@python# python yotube_most_view.py
チャンネルID: UCZf__ehlCEBPop-_sldpBUQ
最も再生された動画: 風船飛ばしたら負け #Shorts (637191383 回再生)
URL: https://www.youtube.com/watch?v=hnBI5OqSXWQ
(venv) root@python#

意外にも、HIKAKINさんの中で一番再生されたのはショート動画で6.3億回再生
海外の人でも楽しめる動画だからだろうか:relieved:
それにしても規格外の再生数

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?