LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 3 years have passed since last update.

extracting youtube video id from youtube URL

Last updated at Posted at 2021-02-05

youtube video id

extract_video_id.py
from urllib.parse import urlparse, parse_qs


urltext = 'https://www.youtube.com/watch?v=T99Ng11MPdY'

def extract_video_id(url):
    query = urlparse(url)
    if query.hostname == 'youtu.be': return query.path[1:]
    if query.hostname in {'www.youtube.com', 'youtube.com'}:
        if query.path == '/watch': return parse_qs(query.query)['v'][0]
        if query.path[:7] == '/embed/': return query.path.split('/')[2]
        if query.path[:3] == '/v/': return query.path.split('/')[2]
    # fail?
    return None

if __name__ == "__main__":

    args = [urltext]
    video_id = ''

    for url in args:
        video_id = (extract_video_id(url))
        print(video_id)

ref.
https://stackoverflow.com/questions/4356538/how-can-i-extract-video-id-from-youtubes-link-in-python/63662923#63662923

Cf.
Extracting video id from YouTube URL and extractiong subtitles to subtitle.txt

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up