我是 Python 新手,过去只使用过 PHP 5(现在很多年前)。作为一个初学者项目,我想我会使用 pytube 制作一个 YouTube 下载器,让您可以选择是下载最高质量的视频还是只下载 .mp3 格式的音频。
好吧,我坚持最后一部分:将扩展名更改为 .mp3。
我想要一个我能理解的简单而优雅的解决方案,但我们将不胜感激。
我尝试使用 os.rename() 但不确定如何使其工作。
from pytube import YouTube
import os
yt = YouTube(str(input("Enter the URL of the video you want to download: \n>> ")))
print("Select download format:")
print("1: Video file with audio (.mp4)")
print("2: Audio only (.mp3)")
media_type = input()
if media_type == "1":
video = yt.streams.first()
elif media_type == "2":
video = yt.streams.filter(only_audio = True).first()
else:
print("Invalid selection.")
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> "))
video.download(output_path = destination)
if media_type == "2":
os.rename(yt.title + ".mp4", yt.title + ".mp3")
print(yt.title + "\nHas been successfully downloaded.")
编辑:
昨天我尝试它时它刚刚挂在最后一部分,但我又试了一次,过了一会儿我收到了这个错误消息:
Traceback (most recent call last):
File "Tubey.py", line 42, in <module>
os.rename(yt.title + ".mp4", yt.title + ".mp3")
FileNotFoundError: [WinError 2] The system cannot find the file specified: "Cristobal Tapia de veer - DIRK GENTLY's original score sampler - cut 3.mp4" -> "Cristobal Tapia de veer - DIRK GENTLY's original score sampler - cut 3.mp3"
该文件已下载但未重命名。
最终编辑:(可能)
我终于让它工作了,这主要归功于 J_H。谢谢你容忍我的无能,你是圣人。这是最终成功的完整代码(以防将来偶然发现此问题的其他人也有类似的问题):
from pytube import YouTube
import os
yt = YouTube(str(input("Enter the URL of the video you want to download: \n>> ")))
print("Select download format:")
print("1: Video file with audio (.mp4)")
print("2: Audio only (.mp3)")
media_type = input(">> ")
if media_type == "1":
video = yt.streams.first()
elif media_type == "2":
video = yt.streams.filter(only_audio = True).first()
else:
print("Invalid selection.")
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'
out_file = video.download(output_path = destination)
if media_type == "2":
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
print(yt.title + " has been successfully downloaded.")
我打算把它变成一个长期项目,并在我学到的越多的时候用更多的功能扩展脚本,但现在我很满意。再次感谢。