Saturday, March 12, 2016

Using Youtube API to Download Video by Using Python

youtube3k

Youtube Download Video

偶爾寫寫工作以外的程式,也是很有趣的事情。
這支程式,快速的從Youtube下載新三國影片,很多集,一次全部下載,我實在太愛這部片了。
用python寫的,只是想很快地把這件事做完,程式亂七八糟的,我也不想整理了。

不多說了,以下為代碼。
Developer_key需要自己去申請。

# -*- coding: utf-8 -*-
#!/usr/bin/python
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import dl
DEVELOPER_KEY = "AIXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
BaseURL='https://www.youtube.com/watch?v='
def youtube_search(options, search_index):
  youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  options.q = search_index
  search_response = youtube.search().list(
    q=search_index,
    part="id,snippet",
    maxResults=50#options.max_results,
  ).execute()
  videos = []
  channels = []
  playlists = []
  for search_result in search_response.get("items", []):
    if search_result['snippet']['title']==options.q:
        linkurl = BaseURL + search_result['id']['videoId']
        print linkurl
        print 'got it'
        dl.download(linkurl)
        break;
    else:
        continue
  print ' cannot find the video: %s '%options.q


if __name__ == "__main__":
  argparser.add_argument("--q", help="Search term", default="三國")
  argparser.add_argument("--max-results", help="Max results", default=50)
  args = argparser.parse_args()
  print args
  for loop in range(1,100):
      if loop <10:
         search_index=u'新三國演義 2010 DVD 0%s'%loop
      else:
         search_index=u'新三國演義 2010 DVD %s'%loop

      print 'search %s'%search_index
      try:
        youtube_search(args, search_index)
      except HttpError, e:
        print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
        

No comments:

Post a Comment