I often see the method of using google-api-python-client as a method to get Youtube data such as the number of views by specifying videoId in pyhton. Here, instead of that method, I tried to get it with https using requests.
It is assumed that the API key of Youtube Data API has been obtained.
Youtube data can be obtained in the following URL format.
www.googleapis.com/youtube/v3/videos?part=statistics&id=★ID★&fields=items%2Fstatistics&key=★APIキー★
ID ... videoId API key ... API key for Youtube Data API
The result will be returned in Json format as follows.
{'items': [{'statistics': {'viewCount': '267', 'likeCount': '3', 'dislikeCount': '0', 'favoriteCount': '0', 'commentCount': '0'}}]}
If you want to get only the number of views (viewCount)
You can get it below assuming that res contains the result.
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
Recommended Posts