【问题标题】:How to extract all .mp4 with youtube-dl in Python?如何在 Python 中使用 youtube-dl 提取所有 .mp4?
【发布时间】:2017-12-05 20:12:44
【问题描述】:

我正在尝试编写一个 Python 脚本,该脚本可以提取 .mp4 文件格式的任何视频的下载链接。为此,我使用youtube-dl,但它以 .m3u8 文件格式返回视频链接。如何获得 .mp4 文件格式?

【问题讨论】:

  • 我猜你需要把它转换成mp4格式。

标签: python youtube youtube-dl


【解决方案1】:

格式化mp4代码:

  • 137: 1080p
  • 136: 720p
  • 135: 480p
  • 134: 360p
  • 133: 240p

    import youtube_dl
    
    url = 'https://twitter.com/PassengersMovie/status/821025484150423557'
    
    with youtube_dl.YoutubeDL({'format':'137'}) as ydl:
        ydl.download([url])
    

【讨论】:

  • 如果我想提取所有可供下载的 .mp4 格式怎么办。
  • 在代码中添加循环例如for f in range(3, 8): with youtube_dl.YoutubeDL({'format':'13' + str(f)}) as ydl: ...
  • 以上答案自 14.02.21 起无法使用最新的 Linut Mint apt-install(下载版本 2016.02.22 -“YouTube 说:参数无效”
【解决方案2】:

您可以使用以下脚本并仅编辑download_list

import youtube_dl
from enum import Enum


class YLFormat(Enum):
    m4a = '140'  # audio only
    mp4_144p = '160'
    mp4_240p = '133'
    mp4_360p = '134'
    mp4_480p = '135'
    mp4_720p = '136'
    mp4_1080p = '137'
    gp3_176_144 = '17'  # 3gp: 176*144
    gp3_320_240 = '36'
    flv = '5'
    webm = '43'
    mp4_640_360 = '18'  # 640 * 360
    mp4_1280_720 = '22'


def download(url: str, options: dict):
    with youtube_dl.YoutubeDL(options) as ydl:
        ydl.download([url])


download_list = [  # edit this
    ('https://www.youtube.com/watch?v=vbttZVTSJRU', YLFormat.mp4_640_360, YLFormat.mp4_1280_720, ...),
]

for cur_data in download_list:
    cur_url, tuple_format = cur_data[0], cur_data[1:]
    for format_info in tuple_format:
        if not isinstance(format_info, YLFormat):
            print(f'the format is not correct. format: {format_info}')
            continue
        fmt_name, fmt = format_info.name, format_info.value
        try:
            download(cur_url, dict(format=fmt,
                                   outtmpl=f'%(title)s-{fmt_name}.%(ext)s',
                                   # ignoreerrors=True,
                                   # quiet=True
                                   ))
        except youtube_dl.utils.DownloadError:
            print(f'download error: {cur_url} | {fmt_name}')

【讨论】:

  • 以上答案从 14.02.21 开始无法使用最新的 Linut Mint apt-install(下载版本 2016.02.22 - 实际终端输出为“格式不正确。格式:{format_info}”所以不确定 format_info 参数
  • @Hektor 你应该看清楚答案,我说edit download_list,所以如果你只是复制粘贴,请将...download_list中删除。
  • 我尝试更新 youtube-dl,然后重新运行它仍然可以。 (操作系统:Windows 10,youtube-dl 版本:2021.02.10,Python:3.7.4
  • 是的,谢谢,我必须下载最新版本的 youtube-dl,因为 Mint 存储库显然已经过时 5 年了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 1970-01-01
  • 2012-12-20
  • 2013-08-05
  • 2020-04-01
  • 2014-07-06
相关资源
最近更新 更多