This is the first post to Qiita. Basically, I plan to use it as my memorandum. I'm still studying Python, so please point out any rushes regarding the code.
Also, regarding copyright etc., we recognize that it is possible within the scope of private use, but please point out if there is any problem.
First, access https://console.cloud.google.com/ to create a project, enable the Youtube Data API from the library, and add credentials (API Key).
Next, install the library required to use the Youtube Data API, and install Youtube_DL required to save the video.
pip install google-api-python-client
pip install youtube-dl
Once installed, first import the library and assign it to each variable.
from apiclient import discovery
import youtube_dl
DEVELOPER_KEY = "" #API Key here
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [
{'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'},
{'key': 'FFmpegMetadata'},
],
} # youtube-Convert videos downloaded with dl to music
If you want to download videos instead of music, you can empty ytdl_opts.
Next, get the URL of the most played video on the channel from 0-10.
def youtube_search(channelId):
videos = [] #List to put URL
youtube = discovery.build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
part="snippet",
channelId= channelId,
maxResults=10,
order="viewCount",
).execute() #After specifying the channel with API, search 10 videos in order of the number of views
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
print("https://www.youtube.com/watch?v=" + search_result['id']['videoId'])
videos.append(search_result["id"]["videoId"]) #Add URL to videos
return videos
By the way, the number of searches can be arbitrarily specified up to maxResults = 0-50.
Download all videos with URLs listed at the end
def download_video(video_list):
for i, videoId in enumerate(video_list): #Turn index number and element at the same time
# ydl_opts['outtmpl'] = "music{}".format(str(i)) + '.%(ext)s' #If you want to make it easier to understand the order of the number of views, here#If you remove music0-10.mp3(mp4)Can be downloaded as
ydl = youtube_dl.YoutubeDL(ydl_opts)
ydl.extract_info("https://www.youtube.com/watch?v={}".format(videoId), download=True)
# ytdl_opts=...The part of shows the format of the file name.
#If you erase music[0-10].mp3(mp4)You can download it in the format of.
A form that can be used by executing the code as it is
from apiclient import discovery
import youtube_dl
DEVELOPER_KEY = "YOUR_API_KEY" #Please enter the API Key here
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [
{'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192'},
{'key': 'FFmpegMetadata'},
],
} # youtube-Convert videos downloaded with dl to music
def youtube_search(channelId):
videos = [] #List to put URL
youtube = discovery.build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(
part="snippet",
channelId= channelId,
maxResults=10,
order="viewCount",
).execute() #After specifying the channel with API, search 10 videos in order of the number of views
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
print("https://www.youtube.com/watch?v=" + search_result['id']['videoId'])
videos.append(search_result["id"]["videoId"]) #Add URL to videos
return videos
def download_video(video_list):
for i, videoId in enumerate(video_list): #Turn index number and element at the same time
# ydl_opts['outtmpl'] = "music{}".format(str(i)) + '.%(ext)s' #If you want to make it easier to understand the order of the number of views of each video, click here#If you remove music0-10.You can download it as an mp3
ydl = youtube_dl.YoutubeDL(ydl_opts)
ydl.extract_info("https://www.youtube.com/watch?v={}".format(videoId), download=True)
if __name__ == '__main__':
channel = input("Please enter the channel ID:")
videos = youtube_search(channel)
download_video(videos)
print('The download is complete.')
This article ends here. Thank you very much.
Recommended Posts