|
| 1 | +#!/usr/bin/python |
| 2 | + |
| 3 | +from apiclient.discovery import build |
| 4 | +from apiclient.errors import HttpError |
| 5 | +from oauth2client.tools import argparser |
| 6 | + |
| 7 | + |
| 8 | +# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps |
| 9 | +# tab of |
| 10 | +# https://cloud.google.com/console |
| 11 | +# Please ensure that you have enabled the YouTube Data API for your project. |
| 12 | +DEVELOPER_KEY = "REPLACE_ME" |
| 13 | +YOUTUBE_API_SERVICE_NAME = "youtube" |
| 14 | +YOUTUBE_API_VERSION = "v3" |
| 15 | + |
| 16 | +def youtube_search(options): |
| 17 | + youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, |
| 18 | + developerKey=DEVELOPER_KEY) |
| 19 | + |
| 20 | + # Call the search.list method to retrieve results matching the specified |
| 21 | + # query term. |
| 22 | + search_response = youtube.search().list( |
| 23 | + q=options.q, |
| 24 | + type="video", |
| 25 | + location=options.location, |
| 26 | + locationRadius=options.location_radius, |
| 27 | + part="id,snippet", |
| 28 | + maxResults=options.max_results |
| 29 | + ).execute() |
| 30 | + |
| 31 | + search_videos = [] |
| 32 | + |
| 33 | + # Merge video ids |
| 34 | + for search_result in search_response.get("items", []): |
| 35 | + search_videos.append(search_result["id"]["videoId"]) |
| 36 | + video_ids = ",".join(search_videos) |
| 37 | + |
| 38 | + # Call the videos.list method to retrieve location details for each video. |
| 39 | + video_response = youtube.videos().list( |
| 40 | + id=video_ids, |
| 41 | + part='snippet, recordingDetails' |
| 42 | + ).execute() |
| 43 | + |
| 44 | + videos = [] |
| 45 | + |
| 46 | + # Add each result to the list, and then display the list of matching videos. |
| 47 | + for video_result in video_response.get("items", []): |
| 48 | + videos.append("%s, (%s,%s)" % (video_result["snippet"]["title"], |
| 49 | + video_result["recordingDetails"]["location"]["latitude"], |
| 50 | + video_result["recordingDetails"]["location"]["longitude"])) |
| 51 | + |
| 52 | + print "Videos:\n", "\n".join(videos), "\n" |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + argparser.add_argument("--q", help="Search term", default="Google") |
| 57 | + argparser.add_argument("--location", help="Location", default="37.42307,-122.08427") |
| 58 | + argparser.add_argument("--location-radius", help="Location radius", default="5km") |
| 59 | + argparser.add_argument("--max-results", help="Max results", default=25) |
| 60 | + args = argparser.parse_args() |
| 61 | + |
| 62 | + try: |
| 63 | + youtube_search(args) |
| 64 | + except HttpError, e: |
| 65 | + print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content) |
| 66 | + |
0 commit comments