编写 python 使用 youtube-dl 仅提取下载 link 的脚本?

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

我是 python 的新手,我正在编写一个 python 脚本来使用 youtube-dl 仅提取下载 link,就像给定的 link通过控制台 (youtube-dl --get-url url)。 我不想下载媒体,我只需要从我的脚本中下载-link。

>>> 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'

如果有多种媒体格式,则获取最后一种格式的媒体 url:

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

ydl = YoutubeDL()
url = 'https://youtu.be/x0RXU3n1GM0'
r = ydl.extract_info(url, download=False)
# if any link will do 
urls = [format['url'] for format in r['formats']]

# if you want links with video and audio
urls = [f['url'] for f in r['formats'] if f['acodec'] != 'none' and f['vcodec'] != 'none']