如何获取使用Youtube-dl下载的文件的文件名

7

我正在使用youtube-dl和flask应用程序下载文件并返回文件。当我下载文件时,文件名会略微从视频标题中更改。查看源代码后,我认为在utils.py中的encodeFilename函数中找到了它。然而,这仍然不匹配,我无法返回文件。

如何获取文件名或替换已下载的文件名?

以下是我的当前代码:

def preferredencoding():
    try:
        pref = locale.getpreferredencoding()
        'TEST'.encode(pref)
    except Exception:
        pref = 'UTF-8'

    return pref


def get_subprocess_encoding():
    if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
        encoding = preferredencoding()
    else:
        encoding = sys.getfilesystemencoding()
    if encoding is None:
        encoding = 'utf-8'
    return encoding


@app.route('/api/v1/videos', methods=['GET'])
def api_id():
    if 'link' in request.args:
        link = request.args['link']
        print("Getting YouTube video")
        try:
            title = youtube_dl.YoutubeDL().extract_info(link, download=False)["title"]
            print(title.encode(get_subprocess_encoding(), 'ignore'))
            print(title)
            code=link.split('v=')[1]
            youtube_dl.YoutubeDL().download([link])
            return send_from_directory(r'C:\Users\User123', title+'-'+code+'.mp4')
        except:
            return "<h1>Error</h1>
2个回答

6
class FilenameCollectorPP(youtube_dl.postprocessor.common.PostProcessor):
    def __init__(self):
        super(FilenameCollectorPP, self).__init__(None)
        self.filenames = []

    def run(self, information):
        self.filenames.append(information['filepath'])
        return [], information
    
filename_collector = FilenameCollectorPP()

my_youtube_dl = youtube_dl.YoutubeDL()
my_youtube_dl.add_post_processor(filename_collector)

# do some downloading, then look inside filename_collector.filenames

https://github.com/ytdl-org/youtube-dl/issues/27192#issuecomment-738004623的启发


示例用法在此处:https://gist.github.com/jmilldotdev/b107f858729064daa940057fc9b14e89 - orangecaterpillar

3

PostProcessor如果ffmpeg崩溃(或您杀死了ffmpeg进程以停止下载),将不会提供文件名。
相反,我们从网站读取视频/流信息,提取文件名,然后开始下载。

import yt_dlp

file_path = ""
with yt_dlp.YoutubeDL() as ydl:
    info = ydl.extract_info(url, download=False)
    file_path = ydl.prepare_filename(info)

    ydl.process_info(info)  # starts the download

记住,如果ffmpeg崩溃,文件也会带有.part扩展名。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接