youtube_dl.utils.SameFileError | python、youtube_dl

youtube_dl.utils.SameFileError | python, youtube_dl

我是 youtube_dl 的新手,我想下载 mp3 格式的 youtube 播放列表,经过大量研究后,我能够编写代码:

import youtube_dl
from time import sleep
# the playlist url
yt_url = input('Enter playlist URL: ')

print('Fetching playlist...')
# Gets the playlist and stores the video info in a list
ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})
with ydl:
    result = ydl.extract_info(yt_url, download=False)
    if 'entries' in result:
        video = result['entries']
        
        playlist = []
        for i, item in enumerate(video):
            video = result['entries'][i]
            playlist.append(video)

# Looping the list to download all the videos one by
# one, named as 1.mp3, 2.mp3, 3.mp3 and so on
a = 0
for video in playlist:
    a = a + 1
    ydl_opts = {'outtmpl': f'{a}.mp3'}
    print(f"\nDownloading {video['title']} (https://youtube.com/watch?v={video['id']}) as {a}.mp3...")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(f"https://youtube.com/watch?v={video['id']}")
    sleep(0.5)
    print('Done.')
print('\n\nTask Finished.')

但我不断收到此错误:

Downloading otherside (https://youtube.com/watch?v=kK81m-A3qpU) as 1.mp3...
Traceback (most recent call last):
  File "/storage/emulated/0/! workspace/goffy/files/bots/music/a/download.py", line 27, in <module>
    ydl.download(f"https://youtube.com/watch?v={video['id']}")
  File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/youtube_dl/YoutubeDL.py", line 2063, in download
    raise SameFileError(outtmpl)
youtube_dl.utils.SameFileError: 1.mp3

我什至没有任何名为 1.mp3 的文件,我只有一个名为 download.py 的文件,其中包含该代码。

谢谢。

尝试将下载 URL 放入列表中,因为这是 download 函数所期望的:

        ydl.download([f"https://youtube.com/watch?v={video['id']}"])

然后引发 SameFileError 异常的 this check 应该通过,因为 len(url_list) 将为 1。

目前 len(url_list) 是 URL 中的字符数,因为它没有包含在 list.