如何从python程序使用youtube-dl

问题描述 投票:73回答:5

我想访问shell命令的结果:

youtube-dl -g "www.youtube.com..."

将其输出direct url打印到文件;从python程序中:

import youtube-dl
fromurl="www.youtube.com ...."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)

有可能吗?我试图了解源代码中的机制,但迷路了:youtube_dl/__init__.pyyoutube_dl/youtube_DL.pyinfo_extractors ...

python youtube-dl
5个回答
122
投票

这并不困难,actually documented

import youtube_dl

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})

with ydl:
    result = ydl.extract_info(
        'http://www.youtube.com/watch?v=BaW_jenozKc',
        download=False # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

print(video)
video_url = video['url']
print(video_url)

4
投票

这是一种方法。

我们在列表中设置选项的字符串,就像我们设置命令行参数一样。在这种情况下为opts=['-g', 'videoID']。然后,调用youtube_dl.main(opts)。通过这种方式,我们编写了自定义.py模块import youtube_dl,然后调用了main()函数。


0
投票

对于简单代码,也许我认为

import os
os.system('youtube-dl [OPTIONS] URL [URL...]')

上面只是在python内部运行命令行。

文档Using youtube-dl on python中提到了其他这是方法

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

-2
投票

如果youtube-dl是终端程序,则可以使用subprocess模块访问所需的数据。

查看此链接以获取更多详细信息:Calling an external command in Python


-4
投票

我想要这个

from subprocess import call

command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)
© www.soinside.com 2019 - 2024. All rights reserved.