To get English captions from a YouTube video URL, the YouTube Transcript API is the most effective solution. This Python library allows you to easily retrieve subtitles without needing to download the video or process audio. Here's a complete, up-to-date implementation:
# Install the required package if you haven't already
# pip install youtube-transcript-api
from youtube_transcript_api import YouTubeTranscriptApi
import re
import json
def get_video_id(youtube_url):
"""Extract the video ID from a YouTube URL."""
# Handle different YouTube URL formats
video_id_match = re.search(r'(?:v=|\/)([0-9A-Za-z_-]{11}).*', youtube_url)
if video_id_match:
return video_id_match.group(1)
return None
def get_english_captions(youtube_url, save_to_file=True, filename=None):
"""
Get English captions from a YouTube video.
Args:
youtube_url (str): The URL of the YouTube video
save_to_file (bool): Whether to save the captions to a file
filename (str): The name of the file to save the captions to
Returns:
list: A list of dictionaries containing the captions
"""
video_id = get_video_id(youtube_url)
if not video_id:
print("Error: Invalid YouTube URL")
return None
try:
# Get the transcript in English
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en'])
if save_to_file:
if not filename:
filename = f"{video_id}_captions.txt"
# Save as plain text
with open(filename, 'w', encoding='utf-8') as txt_file:
for entry in transcript:
start_time = entry['start']
# Convert seconds to HH:MM:SS format
hours, remainder = divmod(start_time, 3600)
minutes, seconds = divmod(remainder, 60)
time_str = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
txt_file.write(f"[{time_str}] {entry['text']}\n")
# Also save as JSON for more detailed information
with open(f"{video_id}_captions.json", 'w', encoding='utf-8') as json_file:
json.dump(transcript, json_file, indent=2)
print(f"Captions saved to {filename} and {video_id}_captions.json")
return transcript
except Exception as e:
print(f"Error: {str(e)}")
# Handle case where English captions aren't available
try:
# List available transcripts
transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
print("Available caption languages:")
for transcript in transcript_list:
print(f"- {transcript.language_code} ({'manually created' if transcript.is_generated else 'auto-generated'})")
# Try to get any available transcript and translate to English
print("Attempting to retrieve and translate available captions...")
foreign_transcript = transcript_list.find_transcript(['en'])
english_transcript = foreign_transcript.translate('en').fetch()
if save_to_file:
if not filename:
filename = f"{video_id}_translated_captions.txt"
with open(filename, 'w', encoding='utf-8') as txt_file:
for entry in english_transcript:
start_time = entry['start']
hours, remainder = divmod(start_time, 3600)
minutes, seconds = divmod(remainder, 60)
time_str = f"{int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}"
txt_file.write(f"[{time_str}] {entry['text']}\n")
print(f"Translated captions saved to {filename}")
return english_transcript
except:
print("No captions available for this video or translation failed.")
return None
# Example usage
if __name__ == "__main__":
# Get input from user
video_url = input("Enter YouTube video URL: ")
captions = get_english_captions(video_url)
# Display first few captions as a preview
if captions:
print("\nPreview of captions:")
for i, caption in enumerate(captions[:5]):
print(f"[{caption['start']:.2f}s] {caption['text']}")
print("...")
Features of This Implementation
- URL Parsing: Extracts video ID from various YouTube URL formats
- Language Selection: Retrieves English captions by default
- Error Handling: Provides informative error messages
- Translation: Attempts to translate captions if English isn't available
- Format Options: Saves captions in both human-readable text and structured JSON
- Time Formatting: Converts timestamp seconds to readable HH:MM:SS format
- Transcript Information: Displays whether captions were manually created or auto-generated[2][3]
Advanced Options
If you need additional functionality, the YouTube Transcript API offers several other features:
- Translation: Translate captions to different languages
- Format Customization: Output captions in various formats
- Auto vs. Manual: Filter by automatically or manually created captions
- Batch Processing: Get transcripts for multiple videos at once[2]
For more complex scenarios, such as videos where captions aren't available at all, you might need to consider using a speech recognition model like Whisper to generate captions from the audio[7].
This solution is much more reliable than parsing YouTube pages directly (which can break with site updates) or using more complex API credentials[6].