動かざることバグの如し

近づきたいよ 君の理想に

YouTube登録しているチャンネルの全一覧をCSVエクスポートしたい

やりたいこと

自分の登録しているYouTubeの全チャンネルをCSVエクスポートしたい

用意するもの

事前準備

google-api-python-clientが必要

pip install google-api-python-client

Pythonコード

import csv
from googleapiclient.discovery import build

# YouTube Data APIのAPIキーを設定します
API_KEY = "**********"

# ユーザー名またはチャンネルIDを指定します
channel_id = "**********"

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

subscription_response = youtube.subscriptions().list(
    part='snippet',
    channelId=channel_id,
    maxResults=50  # 一度に取得できる最大数は50です
).execute()

with open('subscriptions.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['Channel URL', 'Channel Title'])  # ヘッダーを書き込みます

    for item in subscription_response['items']:
        title = item['snippet']['title']
        subscribed_channel_id = item['snippet']['resourceId']['channelId']
        # description = item['snippet']['description']
        url = f"https://www.youtube.com/channel/{item['snippet']['resourceId']['channelId']}"
        writer.writerow([url, title])

そうすると以下のようなCSVが生成できる。

Channel Title,Channel URL
テレビ愛媛ニュース,https://www.youtube.com/channel/UCISf7aH1HqBtTD9jPgzIfVA
テレビ大阪ニュース,https://www.youtube.com/channel/UCd6GEK664CTEWRZda7Fu7Lg

が、 maxResults=50 にもあるようにAPIでは1リクエストで50チャンネルしか取得できない。

もっと取得したい場合は pageToken を利用してループさせる必要がある。

import csv
from googleapiclient.discovery import build

# YouTube Data APIのAPIキーを設定します
API_KEY = "**********"

# ユーザー名またはチャンネルIDを指定します
channel_id = "**********"

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

def get_subscriptions(pageToken=''):
    return youtube.subscriptions().list(
        part='snippet',
        channelId=channel_id,
        maxResults=50,  # 一度に取得する最大数を50に設定します(APIの制限)
        pageToken=pageToken  # 次のページへ進むためのトークン
    ).execute()

with open('subscriptions.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(['Channel Title', 'Channel URL'])

    pageToken = ''
    while True:
        result = get_subscriptions(pageToken)
        for item in result['items']:
          title = item['snippet']['title']
          url = f"https://www.youtube.com/channel/{item['snippet']['resourceId']['channelId']}"]
          # description = item['snippet']['description']
          writer.writerow([title, url])

        if 'nextPageToken' in result:
            pageToken = result['nextPageToken']
        else:
            break

これで50件以上100件だろうが200件でも取得できる。やったね