📅  最后修改于: 2023-12-03 15:06:06.567000             🧑  作者: Mango
The Youtube Data API enables developers to interact with Youtube data, such as videos, playlists, and channels. In this guide, we will cover how to use the Youtube API with Python in the Shell/Bash environment.
Before using the Youtube API, you will need:
You will also need to install the Google APIs Client Library for Python by running the following command:
pip install google-api-python-client
To authenticate your requests to the Youtube API, you will need to create OAuth2 credentials. Follow these instructions to create OAuth2 credentials for your project.
Once you have created your credentials, store them as environment variables in your shell session by running the following commands:
export GOOGLE_CLIENT_ID="YourClientID"
export GOOGLE_CLIENT_SECRET="YourClientSecret"
export GOOGLE_REDIRECT_URI="urn:ietf:wg:oauth:2.0:oob"
To make requests to the Youtube API, you will need to create a service object using the build()
function:
from googleapiclient.discovery import build
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
Replace DEVELOPER_KEY
with your project's API key.
You can then make requests to the API using the youtube
object. For example, to search for videos, you can use the search().list()
method:
search_response = youtube.search().list(
q='cats',
type='video',
part='id,snippet',
maxResults=25
).execute()
Here is an example script that downloads the top 5 videos for a given search query:
import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.errors import HttpError
from googleapiclient.discovery import build
from pytube import YouTube
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def authenticate():
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/youtube.force-ssl']
)
credentials = flow.run_local_server(
port=8080,
open_browser=True
)
return credentials
def download_videos(query, count):
credentials = authenticate()
youtube = build(
YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
credentials=credentials
)
search_response = youtube.search().list(
q=query,
type='video',
part='id,snippet',
maxResults=count
).execute()
for search_result in search_response.get("items", []):
video_id = search_result["id"]["videoId"]
video_url = f"https://www.youtube.com/watch?v={video_id}"
yt = YouTube(video_url)
stream = yt.streams.filter(progressive=True, file_extension='mp4').first()
if stream:
stream.download(output_path=os.getcwd(), filename=video_id)
print(f"Downloaded: {yt.title}")
if __name__ == "__main__":
download_videos("funny cats", 5)
This script authenticates the user and downloads the top 5 videos for the search query "funny cats".
In this guide, we covered how to use the Youtube API with Python in the Shell/Bash environment. We covered how to authenticate requests, make requests, and provided an example script for downloading videos. With the Youtube API, you can build powerful applications that leverage Youtube's vast collection of videos, playlists, and channels. Happy coding!