0

我是新手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,其中包含该代码。

谢谢。

4

1 回答 1

1

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

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

那么这个引发SameFileError异常的检查应该通过,因为len(url_list)它将是 1。

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

于 2022-01-11T09:11:44.777 回答