Skip to content

Instantly share code, notes, and snippets.

@skyblue3350
Created February 19, 2018 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skyblue3350/005b65c1d2f156d872188842753c677c to your computer and use it in GitHub Desktop.
Save skyblue3350/005b65c1d2f156d872188842753c677c to your computer and use it in GitHub Desktop.
特定のチャンネルから動画を引っ張ってきて付近の動画を検索するスクリプト
import os
import json
from datetime import datetime, timedelta
import pytz
import httplib2
from oauth2client import tools
from oauth2client import client
from oauth2client.file import Storage
# 認証
credentials_path = "credentials.json"
if os.path.exists(credentials_path):
store = Storage(credentials_path)
credentials = store.get()
else:
f = "client.json"
scope = "https://www.googleapis.com/auth/youtube.readonly"
flow = client.flow_from_clientsecrets(f, scope)
flow.user_agent = "youtube live chat viewer"
credentials = tools.run_flow(flow, Storage(credentials_path))
api = credentials.authorize(httplib2.Http())
# 対象チャンネルの動画の取得
channel_url = "https://www.youtube.com/channel/UC4YaOt1yT-ZeyB0OmxHgolA"
channel_id = channel_url.split("/")[-1]
max_results = 10
url = "https://www.googleapis.com/youtube/v3/search?part=snippet"
url += "&channelId=" + channel_id
url += "&maxResults=" + str(max_results)
url += "&order=" + "date"
# 結果の表示
res, data = api.request(url)
data = json.loads(data.decode())
for i, v in enumerate(data["items"]):
print(i + 1, v["snippet"]["title"])
# 対象となる動画の選択
print("select video")
n = input("[1-" + str(max_results) + "]>>")
video = data["items"][int(n) - 1]["snippet"]
dt = datetime.strptime(video["publishedAt"], "%Y-%m-%dT%H:%M:%S.%fZ")
dt = pytz.utc.localize(dt).astimezone(pytz.timezone("Asia/Tokyo"))
print()
# 対象の動画の詳細情報
print("タイトル", video["title"])
print("投稿日時", dt.strftime("%Y/%m/%d %H:%M:%S"))
# 対象の曜日と一週間分の取得
start = dt - timedelta(days=dt.weekday())
end = dt + timedelta(days= 6 - dt.weekday())
print("投稿曜日", ["月", "火", "水", "木", "金", "土", "日"][dt.weekday()], "曜日")
print("開始日", start.strftime("%Y/%m/%d"))
print("開始日", end.strftime("%Y/%m/%d"))
print()
start = pytz.utc.normalize(start.astimezone(pytz.utc)).replace(tzinfo=None)
end = pytz.utc.normalize(end.astimezone(pytz.utc)).replace(tzinfo=None)
# 対象期間に投稿された動画の検索
max_results = 50
url = "https://www.googleapis.com/youtube/v3/search?part=snippet"
url += "&channelId=" + channel_id
url += "&maxResults=" + str(max_results)
url += "&order=" + "date"
url += "&publishedAfter=" + start.isoformat() + "Z"
url += "&publishedBefore=" + end.isoformat() + "Z"
print(url)
# 結果の表示
res, data = api.request(url)
data = json.loads(data.decode())
for i, v in enumerate(data["items"]):
print(i + 1, v["snippet"]["title"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment