Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A script to search for youtube videos (and playlists) in the command line, displaying their url/video id. Works great with youtube-dl.
#!/usr/bin/env python2
# ^ also compatible with python3 ^
# This script executes a search request for the specified search term and prints the results.
# Sample usage:
# python searchTube.py --max-results=10 "megadeth album"
# uses the google api client module for python so make sure you install it
import argparse
from googleapiclient.discovery import build
DEVELOPER_KEY = "EXAMPLE_KEY" # REQUIRES your own API key here, get the key from google developers.
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
# Call the search.list method to retrieve results matching the specified query term:
search_response = youtube.search().list(
q=options.title,
part='id,snippet',
maxResults=options.max_results
).execute()
videos = []
videoIDs = []
videoTimes = []
playlists = []
playlistIDs = []
# Add each result to the appropriate list:
for search_result in search_response.get('items', []):
if search_result['id']['kind'] == 'youtube#video':
videos.append(search_result['snippet']['title'])
videoIDs.append(search_result['id']['videoId'])
elif search_result['id']['kind'] == 'youtube#playlist':
playlists.append(search_result['snippet']['title'])
playlistIDs.append(search_result['id']['playlistId'])
if videos:
requestingID = ""
for ID in videoIDs:
requestingID += ID+","
search_response2 = youtube.videos().list(
part="contentDetails",
id=requestingID
).execute()
for result in search_response2.get('items', []):
contentDetail = result['contentDetails']
videoTimes.append(contentDetail["duration"])
# displays the videos with their duration
print("Videos: http://youtube.com/watch?v=[ID]\n")
for i in range(len(videos)):
out = videos[i] + " | "
time = videoTimes[i]
displayTime = ""
for j in range(2, len(time)):
if time[j].isdigit():
displayTime += time[j]
else:
displayTime += time[j] + " "
out += displayTime + " | "
out += videoIDs[i]
print(out)
# displays the playlists
print("\nPlaylists: https://www.youtube.com/playlist?list=[ID]\n")
for i in range(len(playlists)):
out = playlists[i]
out += " | " + playlistIDs[i]
print(out)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('title', help='Title to search for') # required
parser.add_argument('--max-results', help='Maximum number of results to display', default=10)
args = parser.parse_args()
youtube_search(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment