DEV Community

tamilvanan
tamilvanan

Posted on

Get YouTube Transcript Using Python (macOS)

Get YouTube Transcript Using Python (macOS)

Need a quick way to extract a YouTube transcript into a Markdown file? Copy, paste, and run.

1. Create project folder and VENV

mkdir youtube-transcript
cd youtube-transcript

python3 -m venv venv
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

2. Install dependency

pip3 install youtube-transcript-api
Enter fullscreen mode Exit fullscreen mode

3. Create Python file

touch transcript.py
Enter fullscreen mode Exit fullscreen mode

Open it:

nano transcript.py
Enter fullscreen mode Exit fullscreen mode

Paste:

from youtube_transcript_api import YouTubeTranscriptApi
from urllib.parse import urlparse, parse_qs

url = input("Enter YouTube URL: ")

parsed_url = urlparse(url)
video_id = parse_qs(parsed_url.query).get("v", [None])[0]

if not video_id:
    print("Invalid YouTube URL")
    exit()

ytt_api = YouTubeTranscriptApi()
transcript = ytt_api.fetch(video_id)

filename = f"{video_id}.md"

with open(filename, "w", encoding="utf-8") as f:
    f.write(f"# Transcript - {video_id}\n\n")

    for line in transcript:
        f.write(f"{line.text}\n\n")

print(f"Saved transcript to {filename}")
Enter fullscreen mode Exit fullscreen mode

Save:

CTRL + O
ENTER
CTRL + X
Enter fullscreen mode Exit fullscreen mode

4. Run

python3 transcript.py
Enter fullscreen mode Exit fullscreen mode

Example:

Enter YouTube URL:
https://youtube.com/watch?v=VIDEO_ID
Enter fullscreen mode Exit fullscreen mode

Output:

Saved transcript to VIDEO_ID.md
Enter fullscreen mode Exit fullscreen mode

Open transcript:

cat VIDEO_ID.md
Enter fullscreen mode Exit fullscreen mode

Done.

Top comments (0)