Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@desilinguist
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save desilinguist/d1eca38817acf227f7cc to your computer and use it in GitHub Desktop.
Save desilinguist/d1eca38817acf227f7cc to your computer and use it in GitHub Desktop.
Downloading YouTube videos from titles in a filename.
python geturls.py --f test.txt | cut -d'|' -f2 | youtube-dl -a -
#!/usr/bin/env python
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "YOUR KEY HERE"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(search_term):
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=search_term,
part="id,snippet",
maxResults=1
).execute()
videos = []
# save the video results
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append((search_result["snippet"]["title"],
search_result["id"]["videoId"]))
return videos
if __name__ == "__main__":
argparser.add_argument("--f", help="File containing video titles")
args = argparser.parse_args()
with open(args.f, 'r') as inf:
for line in inf:
search_term = line.strip()
try:
videos = youtube_search(search_term)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
for snippet, vid in videos:
print "%s|http://www.youtube.com/watch?v=%s" % (snippet.replace('|', ''), vid)
@desilinguist
Copy link
Author

  1. Works only with Python 2.7
  2. You need to install Google Python API, OAuth Client, and youtube-dl using pip.
  3. You need to obtain a YouTube API developer key (see here) and put it in the python script.

@dan-blanchard
Copy link

No Python 3? You disappoint me Nitin. 😦

@desilinguist
Copy link
Author

youtube-dl only works with Python 2.7 at this point so I can't do anything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment