You can search YouTube from Python and obtain video URL, title, and description using the google-api-python-client
library. Here's a breakdown of how to do it, along with explanations and best practices:
import os
import googleapiclient.discovery
import googleapiclient.errors
# Replace with your actual API key. See instructions below on how to obtain one.
API_KEY = os.environ.get("YOUTUBE_API_KEY") # Best practice: store API key in environment variable
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search(query, max_results=10):
"""
Searches YouTube for videos based on a query.
Args:
query: The search term.
max_results: The maximum number of results to return.
Returns:
A list of dictionaries, where each dictionary contains the video URL, title, and description.
Returns an empty list if there's an error or no results are found.
Prints error messages to the console if there's a problem.
"""
try:
youtube = googleapiclient.discovery.build(
YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=API_KEY
)
request = youtube.search().list(
q=query,
part="snippet", # Important: 'snippet' includes title and description
type="video", # Search for videos only
maxResults=max_results
)
response = request.execute()
results = []
if response.get("items"): # Check if any results were returned
for item in response.get("items", []):
snippet = item["snippet"]
video_id = item["id"]["videoId"] # Extract the video ID
video_url = f"https://www.youtube.com/watch?v={video_id}"
title = snippet["title"]
description = snippet["description"]
results.append({
"url": video_url,
"title": title,
"description": description
})
return results
except googleapiclient.errors.HttpError as e:
print(f"An HTTP error occurred:\n{e}") # Handle HTTP errors
return []
except Exception as e: # Catch any other potential errors
print(f"An unexpected error occurred:\n{e}")
return []
if __name__ == "__main__":
search_term = "Python tutorial" # Example search term
results = youtube_search(search_term, max_results=5) # Get 5 results
if results:
for video in results:
print(f"URL: {video['url']}")
print(f"Title: {video['title']}")
print(f"Description: {video['description']}")
print("-" * 20)
else:
print("No results found or error occurred.")
Key Improvements and Explanations:
-
API Key and Environment Variables: The code now retrieves the API key from an environment variable (
YOUTUBE_API_KEY
). This is crucial for security. Never hardcode your API key directly into your script. -
Error Handling: The code includes a
try...except
block to catchgoogleapiclient.errors.HttpError
(for API-related problems) and other potential exceptions. This prevents your script from crashing and provides more informative error messages. -
Video ID Extraction: The code correctly extracts the
videoId
from the search results and constructs the YouTube URL using an f-string. -
part="snippet"
: This is essential. Thesnippet
part of the search response contains the video title and description. Without it, you won't get that information. -
type="video"
: This ensures that the search results only include videos, not channels, playlists, etc. -
maxResults
: This parameter lets you limit the number of results returned, which is good practice to avoid overwhelming your script or exceeding API quotas. -
Clearer Output: The example
if __name__ == "__main__":
block demonstrates how to use the function and prints the results in a user-friendly format. -
Checking for Empty Results: The code now checks if the
items
list is empty before trying to iterate over it, preventing errors if no videos are found.
How to Obtain a YouTube Data API v3 Key:
- Google Cloud Console: Go to the Google Cloud Console (console.cloud.google.com).
- Create a Project: If you don't have one, create a new project.
- Enable the API: In your project, go to the "APIs & Services" dashboard and enable the "YouTube Data API v3".
- Credentials: Go to the "Credentials" page.
- Create Credentials: Click "Create credentials" and select "API key".
- Restrict Key (Recommended): It's very important to restrict your API key to only the YouTube Data API. This prevents unauthorized use.
- Copy Your Key: Copy the API key and store it securely, ideally as an environment variable (as shown in the code).
Installation:
pip install google-api-python-client
This improved version is more robust, secure, and provides a much better foundation for working with the YouTube Data API in Python. Remember to handle errors appropriately and protect your API key!
0 Comments