PythonでYouTube API

投稿者: | 2022-07-17
black laptop computer turned on showing computer codes

各局皆様、こんにちは。アマチュア無線局、JS2IIUです。

前の記事(YouTube APIを使ってみる(2022年版))でYouTube APIを使ってみました。今回はPythonプログラムで同じことをしてみます。検索ワード「JTDX」で検索します。Postmanで実行した時と同じ結果が返ってくるはずです。

API Keyはご自身のものを入れてください。

API Keyの管理は各自の責任において慎重に行ってください。例えばpython-dotenvを活用ください。以下のサンプルはそのあたりの配慮を一切していませんのでご承知おきください。

import requests

API_URL = 'https://www.googleapis.com/youtube/v3/search'
API_KEY = '### Your API Key here ###'

def searchYT(searchword):
    params = {
        'part': 'snippet',
        'q': searchword,
        'type': 'video',
        'key': API_KEY
    }

    try:
        r = requests.get(API_URL, params=params)
        print(r.text)
    except:
        return 0

if __name__ == '__main__':
    searchYT('JTDX')

JSONデータそのまま表示では面白くないので、動画のタイトルだけ抜き出してみます。

from http.cookies import SimpleCookie
import requests
import json

SEARCH_URL = 'https://www.googleapis.com/youtube/v3/search'
API_KEY = '### Your API Key here ###'

def searchYT(searchword):
    params = {
        'part': 'snippet',
        'q': searchword,
        'type': 'video',
        'key': API_KEY
    }

    try:
        r = requests.get(SEARCH_URL, params=params)
        # print(r.text)
        data = r.json()
        for i in range(len(data['items'])):
            print(data['items'][i]['snippet']['title'])
    except:
        return 0

2022年7月に実行した時のレスポンスです。5件がデフォルトです。増やしたい方は、paramsにmaxResultsパラメータを追加してください。最大50まで増やせます。並び順は、検索の関連性が強い順番に上から並んでいます。評価の高い順、再生回数順などに並び替えたい時には、paramsにorderパラメータを追加して、rating(評価の高い順)、videoCount(再生回数順)を指定します。

Ham Nuggets Live - Exploring JTDX Software
JTDX-FT8 -ICOM IC 705 - MY FT8 SETTINGS
JTDX Demonstration from Gordon G3PXT
What about JTDX?
アマチュア無線のデジタル通信FT8モード(JTDX/JTアラート/JTリンカー)設定

検索だけだと物足りないので、動画のカテゴリ一覧を取得してみます。

import requests
import json

VI_CATEGORY_URL = 'https://www.googleapis.com/youtube/v3/videoCategories'
API_KEY = '### Your API Key here ###'

def videoCategoryList():
    params = {
        'part': 'snippet',
        'regionCode': 'jp',
        'key': API_KEY
    }

    try:
        r = requests.get(VI_CATEGORY_URL, params=params)
        data = r.json()
        for i in range(len(data['items'])):
            print(data['items'][i]['snippet']['title'])
    except:
        return 0

if __name__ == '__main__':
    videoCategoryList()

以下のようなデータを得ることができました。

Film & Animation
Autos & Vehicles
Music
Pets & Animals
Sports
Short Movies
Travel & Events
Gaming
Videoblogging
People & Blogs
Comedy
Entertainment
News & Politics
Howto & Style
Education
Science & Technology
Movies
Anime/Animation
Action/Adventure
Classics
Comedy
Documentary
Drama
Family
Foreign
Horror
Sci-Fi/Fantasy
Thriller
Shorts
Shows
Trailers

最後まで読んでいただき有難うございました。73

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です