Search code examples
pythonyoutube-dl

Wrting python script that uses youtube-dl to extract just only the download link?


I'm new to python and I'm writing a python script to use youtube-dl to extract only download link, exactly like link given by the console (youtube-dl --get-url url). I don't want to download the media, I just need the download-link from my script.


Solution

  • >>> from youtube_dl import YoutubeDL # $ pip install youtube-dl
    >>> url = 'https://www.youtube.com/watch?v=pvAsqPbz9Ro'
    >>> ydl = YoutubeDL()
    >>> r = ydl.extract_info(url, download=False)
    [youtube] pvAsqPbz9Ro: Downloading webpage
    [youtube] pvAsqPbz9Ro: Downloading video info webpage
    [youtube] pvAsqPbz9Ro: Extracting video information
    [youtube] pvAsqPbz9Ro: Downloading DASH manifest
    [youtube] pvAsqPbz9Ro: Downloading DASH manifest
    >>> r['url']
    u'https://r6---sn-n8v7zne7.googlevideo.com/videoplayback?...&ipbits=0'
    

    If there are several media formats then to get media url for the last format:

    with youtube_dl.YoutubeDL(dict(forceurl=True)) as ydl:
        r = ydl.extract_info(url, download=False)
        media_url = r['formats'][-1]['url']