1
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?

【Python】YouTubeの動画データ分析:Anaconda環境のJupyter Labで特定チャンネルの情報を取得する

1
Posted at

はじめに

特定のYouTubeチャンネルの投稿トレンドや再生数の推移を分析するために、YouTube Data API(v3)を使って動画情報を取得する方法をまとめました。今回は、Pythonを使用して「動画タイトル」と「再生回数」を毎日午前10時に上書きでCSVに書き出すシンプルなスクリプトを紹介します。

準備するもの

  1. Google Cloud Consoleでのプロジェクト作成
  2. YouTube Data API v3の有効化
  3. APIキーの取得
  4. Python環境とライブラリのインストール
pip install google-api-python-client

実装コード

import subprocess
import sys

# 強制的にインストールを実行
subprocess.check_call([sys.executable, "-m", "pip", "install", "schedule", "google-api-python-client"])

import schedule
import time
import csv
import os
from datetime import datetime
from googleapiclient.discovery import build

# --- 設定情報 ---
API_KEY = 'APIキー'
CHANNEL_ID = '取得したいチャンネルID'
EXECUTION_TIME = "10:00"  # 毎日10時に実行
CSV_FILE = 'youtube_stats.csv'

def get_channel_videos_to_csv():
    youtube = build('youtube', 'v3', developerKey=API_KEY)
    
    # 1. アップロード済み動画のプレイリストIDを取得
    ch_response = youtube.channels().list(
        part='contentDetails',
        id=CHANNEL_ID
    ).execute()
    
    uploads_id = ch_response['items'][0]['contentDetails']['relatedPlaylists']['uploads']

    # 2. 動画一覧と再生数を取得
    all_data = []
    now_str = datetime.now().strftime('%Y-%m-%d %H:%M') # 取得日時
    next_page_token = None

    print(f"{now_str} データ取得開始...")

    while True:
        pl_response = youtube.playlistItems().list(
            part='snippet,contentDetails',
            playlistId=uploads_id,
            maxResults=50,
            pageToken=next_page_token
        ).execute()

        # 動画IDのリストを作成(まとめて再生数を取得するため)
        video_ids = [item['contentDetails']['videoId'] for item in pl_response['items']]
        
        # 3. 再生数をまとめて取得(効率化)
        v_response = youtube.videos().list(
            part='statistics,snippet',
            id=','.join(video_ids)
        ).execute()

        for v_item in v_response['items']:
            title = v_item['snippet']['title']
            view_count = v_item['statistics'].get('viewCount', 0)
            all_data.append([now_str, title, view_count])

        next_page_token = pl_response.get('nextPageToken')
        if not next_page_token:
            break

    # 4. CSVファイルへ保存(追記モード)
    file_exists = os.path.isfile(CSV_FILE)
    with open(CSV_FILE, mode='a', newline='', encoding='utf-8-sig') as f:
        writer = csv.writer(f)
        # 新規ファイルの場合のみヘッダー(項目名)を書く
        if not file_exists:
            writer.writerow(['取得日時', '動画タイトル', '再生数'])
        writer.writerows(all_data)

    print(f"CSVへの保存が完了しました。現在の合計動画数: {len(all_data)}")

# 定期実行の設定
schedule.every().day.at(EXECUTION_TIME).do(get_channel_videos_to_csv)

print(f"待機中... (毎日 {EXECUTION_TIME} に実行し、{CSV_FILE} に保存します)")
# 初回テスト実行(すぐに動かしたい場合は以下のコメントアウトを外してください)
get_channel_videos_to_csv()

while True:
    schedule.run_pending()
    time.sleep(60)

チャンネルIDの調べ方

  1. ブラウザでチャンネルのトップページを開きます。
  2. ページの何もないところで右クリックし、**「ページのソースを表示」**を選択します。
  3. Ctrl + F(MacはCommand + F)で検索窓を出して、browse_idと入力して検索します。
  4. その後すぐ後ろにあるUCで始まる24文字の文字列がチャンネルIDです。

おわりに

今回は基本的な情報の取得までを行いました。今後はこれらをPandasでデータフレーム化したり、可視化したりする応用も考えています。

1
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
1
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?