LoginSignup
0
1

More than 3 years have passed since last update.

pyhtonでYoutubeデータを取得する

Posted at

はじめに

pyhtonでvideoIdを指定して再生回数などのYoutubeデータを取得する方法として google-api-python-client を使う方法をよく見かけます。
ここでは、その方法ではなく requestsを使ってhttpsで取得する方法でやってみました。

Youtube Data APIのAPIキーは取得済みとします。

URLの形式

以下のURLの形式でYoutubeデータを取得できます。
www.googleapis.com/youtube/v3/videos?part=statistics&id=★ID★&fields=items%2Fstatistics&key=★APIキー★

ID ... videoId
APIキー ... Youtube Data APIのAPIキー

返却値

結果はJson形式で以下のような形で返ってきます。
{'items': [{'statistics': {'viewCount': '267', 'likeCount': '3', 'dislikeCount': '0', 'favoriteCount': '0', 'commentCount': '0'}}]}
再生回数(viewCount)だけを取得したい場合は
res に結果が入っているとして以下で取得できます。
count = res["items"][0]["statistics"]["viewCount"]

サンプル

sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import json

base_url = "https://www.googleapis.com/youtube/v3/videos?part=statistics&id={}&fields=items%2Fstatistics&key={}"

api_key  = "xxxx"
id = "xxxxx"
url = base_url.format(id,api_key)
res = json.loads(requests.get(url,verify=False).text)
count = res["items"][0]["statistics"]["viewCount"]

print(count)

確認環境

Windows10
Python 3.7.0

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