如何在 Python 程序中使用 youtube-dl?
- 2025-03-13 09:10:00
- admin 原创
- 70
问题描述:
我想访问以下 shell 命令的结果,
youtube-dl -g "www.youtube.com/..."
在 Python 程序中将其输出打印direct url
到文件。这是我尝试过的:
import youtube-dl
fromurl="www.youtube.com/..."
geturl=youtube-dl.magiclyextracturlfromurl(fromurl)
这可能吗?我试图理解源代码中的机制,但迷失了:youtube_dl/__init__.py
,,...youtube_dl/youtube_DL.py
`info_extractors`
解决方案 1:
这并不困难,而且实际上有记录:
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)
解决方案 2:
对于简单的代码,可能我认为
import os
os.system('youtube-dl [OPTIONS] URL [URL...]')
以上只是在 python 内部运行命令行。
其他内容在文档中提到在 python 上使用 youtube-dl
以下是方法
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'])
解决方案 3:
这是一种方法。
我们在列表中设置选项的字符串,就像设置命令行参数一样。在本例中是opts=['-g', 'videoID']
。然后,调用youtube_dl.main(opts)
。这样,我们编写了自定义 .py 模块,import youtube_dl
然后调用该main()
函数。
解决方案 4:
from __future__ import unicode_literals
import youtube_dl
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['Your youtube url'])
您可以在 ydl_opts 中使用“format”、“continue”、“outtmpl”作为示例;
ydl_opts= {
'format': '22',
'continue': True,
'outtmpl': '%(uploader)s - %(title)s.%(ext)s',
'progress_hooks': [my_hook],
}
def my_hook(d):
if d['status'] == 'downloading':
print('Downloading video!')
if d['status'] == 'finished':
print('Downloaded!')
当您需要停止播放列表下载时,只需将此代码添加到ydl_opts中。
'noplaylist': True;
解决方案 5:
用法:python3 AudioFromYtVideo.py link outputName
import os
from sys import argv
try:
if argv[1] and argv[2]:
pass
except:
print("Input: python3 [programName] [url] [outputName]")
os.system('youtube-dl -x --audio-format mp3 -o '+argv[2]+' '+argv[1])
解决方案 6:
如果youtube-dl
是终端程序,您可以使用subprocess
模块来访问您想要的数据。
查看此链接了解更多详细信息:在 Python 中调用外部命令
解决方案 7:
我想要这个
from subprocess import call
command = "youtube-dl https://www.youtube.com/watch?v=NG3WygJmiVs -c"
call(command.split(), shell=False)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD