使用pytube下载mp3格式的视频
Download video in mp3 format using pytube
我一直在使用 pytube 下载 python 中的 youtube 视频。到目前为止,我已经能够以 mp4 格式下载。
yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")
vids= yt.streams.all()
for i in range(len(vids)):
print(i,'. ',vids[i])
vnum = int(input("Enter vid num: "))
vids[vnum].download(r"C:\YTDownloads")
print('done')
我设法下载了 'audio' 版本,但它是 .mp4
格式。我确实尝试将扩展名重命名为 .mp3
,并且播放了音频,但应用程序(Windows 媒体播放器)停止响应并开始延迟。
如何将视频下载为 .mp3
格式 直接 的音频文件?请提供一些代码,因为我是使用此模块的新手。
How can I download the video as an audio file, in .mp3 format directly?
恐怕你不能。唯一可供直接下载的文件是 yt.streams.all()
.
下列出的文件
但是,将下载的音频文件从 .mp4
格式转换为 .mp3
格式很简单。例如,如果您安装了 ffmpeg,运行 来自终端的这个命令就可以解决问题(假设您在下载目录中):
$ ffmpeg -i downloaded_filename.mp4 new_filename.mp3
或者,您可以使用 Python 的 subprocess
模块以编程方式执行 ffmpeg 命令:
import os
import subprocess
import pytube
yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")
vids= yt.streams.all()
for i in range(len(vids)):
print(i,'. ',vids[i])
vnum = int(input("Enter vid num: "))
parent_dir = r"C:\YTDownloads"
vids[vnum].download(parent_dir)
new_filename = input("Enter filename (including extension): ")) # e.g. new_filename.mp3
default_filename = vids[vnum].default_filename # get default name using pytube API
subprocess.run([
'ffmpeg',
'-i', os.path.join(parent_dir, default_filename),
os.path.join(parent_dir, new_filename)
])
print('done')
编辑:删除了对 subprocess.call
的提及。使用 subprocess.run
(除非您使用的是 Python 3.4 或更低版本)
这里有一种更精简和更密集的格式,用于下载 mp4 视频并将 mp4 转换为 mp3:
下载会将文件下载到程序的当前目录或位置,这也会将文件转换为 mp3 作为新文件。
from pytube import YouTube
import os
import subprocess
import time
while True:
url = input("URL: ")
# Title and Time
print("...")
print(((YouTube(url)).title), "//", (int(var1)/60),"mins")
print("...")
# Filename specification
# Prevents any errors during conversion due to illegal characters in name
_filename = input("Filename: ")
# Downloading
print("Downloading....")
YouTube(url).streams.first().download(filename=_filename)
time.sleep(1)
# Converting
mp4 = "'%s'.mp4" % _filename
mp3 = "'%s'.mp3" % _filename
ffmpeg = ('ffmpeg -i %s ' % mp4 + mp3)
subprocess.call(ffmpeg, shell=True)
# Completion
print("\nCOMPLETE\n")
这是一个无限循环,允许重命名、下载和转换多个 URL。
我假设你正在使用Python3和pytube 9.x,你可以使用过滤方法来“过滤”,文件扩展名你有兴趣。
例如,如果您要下载 mp4 视频文件格式,则如下所示:
pytube.YouTube("url here").streams.filter(file_extension="mp4").first()
如果您想提取音频,它看起来如下所示:
pytube.YouTube("url here").streams.filter(only_audio=True).all()
希望对任何登陆此页面的人有所帮助;而不是进行不必要的转换。
使用此代码,您将从播放列表中下载所有视频,并以 mp4 和 mp4 音频格式从 youtube 保存它们和标题。
我在这个问题中使用了@scrpy 的代码和@Jean-Pierre Schnyder 的提示
来自这个answer
import os
import subprocess
import re
from pytube import YouTube
from pytube import Playlist
path =r'DESTINATION_FOLER'
playlist_url = 'PLAYLIST_URL'
play = Playlist(playlist_url)
play._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(play.video_urls))
for url in play.video_urls:
yt = YouTube(url)
audio = yt.streams.get_audio_only()
audio.download(path)
nome = yt.title
new_filename=nome+'.mp3'
default_filename =nome+'.mp4'
ffmpeg = ('ffmpeg -i ' % path default_filename + new_filename)
subprocess.run(ffmpeg, shell=True)
print('Download Complete')
您需要安装 pytubemp3(使用 pip install pytubemp3
)最新版本 0.3 + 然后
from pytubemp3 import YouTube
YouTube(video_url).streams.filter(only_audio=True).first().download()
from pytube import YouTube
yt = YouTube(url)
yt.streams.get_audio_only().download(output_path='/home/',filename=yt.title)
将视频下载为音频,然后将音频扩展名更改为 MP3:
from pytube import YouTube
import os
url = str(input("url:- "))
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
downloaded_file = video.download()
base, ext = os.path.splitext(downloaded_file)
new_file = base + '.mp3'
os.rename(downloaded_file, new_file)
print("Done")
Pytube 不支持“mp3”格式,但您可以下载 webm 格式的音频。下面的代码演示了它。
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
stream = yt.streams.get_by_itag(251)
stream.download()
对于 mp3,您必须将(mp4 或 webm)文件格式转换为 mp3。
Pytube 不支持“mp3”格式,但您可以下载 webm 格式的音频。下面的代码演示了它。
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
stream = yt.streams.get_by_itag(251)
itag 是获取特定分辨率文件的唯一 ID
stream.download()
对于 mp3,您必须将(mp4 或 webm)文件格式转换为 mp3。
尝试使用:
from pytube import YouTube
import os
link = input('enter the link: ')
path = "D:\" #enter the path where you want to save your video
video = YouTube(link)
print( "title is : ", video.title)
#download video
print("title is : ", video.title)
video.streams.filter(only_audio=True).first().download( path , filename ="TemporaryName.Mp4" )
#remove caracters (" | , / \ ..... ) from video title
VideoTitle = video.title
VideoTitle = VideoTitle.replace('\"' , " ")
VideoTitle = VideoTitle.replace('|', " ")
VideoTitle = VideoTitle.replace(',', " ")
VideoTitle = VideoTitle.replace('/"' , " ")
VideoTitle = VideoTitle.replace('\', " ")
VideoTitle = VideoTitle.replace(':', " ")
VideoTitle = VideoTitle.replace('*"' , " ")
VideoTitle = VideoTitle.replace('?', " ")
VideoTitle = VideoTitle.replace('<', " ")
VideoTitle = VideoTitle.replace('>"' , " ")
#change name and converting Mp4 to Mp3
my_file = path + "\" + "TemporaryName.mp4"
base = path + "\" + VideoTitle
print("New Video Title is :" +VideoTitle)
os.rename(my_file, base + '.mp3')
print(video.title, ' \nhas been successfully downloaded as MP3')
这是我的解决方案:
import os
import sys
from pytube import YouTube
from pytube.cli import on_progress
PATH_SAVE = "D:\Downloads"
yt = YouTube("YOUR_URL", on_progress_callback=on_progress)
#Download mp3
audio_file = yt.streams.filter(only_audio=True).first().download(PATH_SAVE)
base, ext = os.path.splitext(audio_file)
new_file = base + '.mp3'
os.rename(audio_file, new_file)
#Download Video
ys = yt.streams.filter(res="1080p").first()
ys.download(PATH_SAVE)
工作:Python v3.9.x 和 pytube v11.0.1
这是我的解决方案:
from os import path, rename
from pytube import YouTube as yt
formato = ""
descarga = desktop = path.expanduser("~/Desktop")
link = input("Inserte el enlace del video: ")
youtube = yt(link)
while formato != "mp3" and formato != "mp4":
formato = input("¿Será en formato mp3 o mp4? ")
if formato == "mp4":
youtube.streams.get_highest_resolution().download(descarga)
elif formato == "mp3":
video = youtube.streams.first()
downloaded_file = video.download(descarga)
base, ext = path.splitext(downloaded_file)
new_file = base + '.mp3'
rename(downloaded_file, new_file)
print("Descarga completa!")
input("Presiona Enter para salir...")
这是我的解决方案。只需使用 pytube 的文件名选项重命名下载内容的名称即可。
url = input("URL of the video that will be downloaded as MP^: ")
try:
video = yt(url)
baslik = video.title
print(f"Title: {baslik}")
loc = input("Location: ")
print(f"Getting ITAG info for {baslik}")
for itag in video.streams.filter(only_audio=True): # It'll show only audio streams.
print(itag)
itag = input("ITAG secimi: ")
print(f"{baslik} sesi {loc} konumuna indiriliyor.")
video.streams.get_by_itag(itag).download(loc, filename=baslik + ".mp3") # And you can rename video by filename= option. Just add .mp3 extension to video's title.
print("Download finished.")
except:
print("Enter a valid URL")
sys.exit()
我一直在使用 pytube 下载 python 中的 youtube 视频。到目前为止,我已经能够以 mp4 格式下载。
yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")
vids= yt.streams.all()
for i in range(len(vids)):
print(i,'. ',vids[i])
vnum = int(input("Enter vid num: "))
vids[vnum].download(r"C:\YTDownloads")
print('done')
我设法下载了 'audio' 版本,但它是 .mp4
格式。我确实尝试将扩展名重命名为 .mp3
,并且播放了音频,但应用程序(Windows 媒体播放器)停止响应并开始延迟。
如何将视频下载为 .mp3
格式 直接 的音频文件?请提供一些代码,因为我是使用此模块的新手。
How can I download the video as an audio file, in .mp3 format directly?
恐怕你不能。唯一可供直接下载的文件是 yt.streams.all()
.
但是,将下载的音频文件从 .mp4
格式转换为 .mp3
格式很简单。例如,如果您安装了 ffmpeg,运行 来自终端的这个命令就可以解决问题(假设您在下载目录中):
$ ffmpeg -i downloaded_filename.mp4 new_filename.mp3
或者,您可以使用 Python 的 subprocess
模块以编程方式执行 ffmpeg 命令:
import os
import subprocess
import pytube
yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")
vids= yt.streams.all()
for i in range(len(vids)):
print(i,'. ',vids[i])
vnum = int(input("Enter vid num: "))
parent_dir = r"C:\YTDownloads"
vids[vnum].download(parent_dir)
new_filename = input("Enter filename (including extension): ")) # e.g. new_filename.mp3
default_filename = vids[vnum].default_filename # get default name using pytube API
subprocess.run([
'ffmpeg',
'-i', os.path.join(parent_dir, default_filename),
os.path.join(parent_dir, new_filename)
])
print('done')
编辑:删除了对 subprocess.call
的提及。使用 subprocess.run
(除非您使用的是 Python 3.4 或更低版本)
这里有一种更精简和更密集的格式,用于下载 mp4 视频并将 mp4 转换为 mp3:
下载会将文件下载到程序的当前目录或位置,这也会将文件转换为 mp3 作为新文件。
from pytube import YouTube
import os
import subprocess
import time
while True:
url = input("URL: ")
# Title and Time
print("...")
print(((YouTube(url)).title), "//", (int(var1)/60),"mins")
print("...")
# Filename specification
# Prevents any errors during conversion due to illegal characters in name
_filename = input("Filename: ")
# Downloading
print("Downloading....")
YouTube(url).streams.first().download(filename=_filename)
time.sleep(1)
# Converting
mp4 = "'%s'.mp4" % _filename
mp3 = "'%s'.mp3" % _filename
ffmpeg = ('ffmpeg -i %s ' % mp4 + mp3)
subprocess.call(ffmpeg, shell=True)
# Completion
print("\nCOMPLETE\n")
这是一个无限循环,允许重命名、下载和转换多个 URL。
我假设你正在使用Python3和pytube 9.x,你可以使用过滤方法来“过滤”,文件扩展名你有兴趣。
例如,如果您要下载 mp4 视频文件格式,则如下所示:
pytube.YouTube("url here").streams.filter(file_extension="mp4").first()
如果您想提取音频,它看起来如下所示:
pytube.YouTube("url here").streams.filter(only_audio=True).all()
希望对任何登陆此页面的人有所帮助;而不是进行不必要的转换。
使用此代码,您将从播放列表中下载所有视频,并以 mp4 和 mp4 音频格式从 youtube 保存它们和标题。
我在这个问题中使用了@scrpy 的代码和@Jean-Pierre Schnyder 的提示 来自这个answer
import os
import subprocess
import re
from pytube import YouTube
from pytube import Playlist
path =r'DESTINATION_FOLER'
playlist_url = 'PLAYLIST_URL'
play = Playlist(playlist_url)
play._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(play.video_urls))
for url in play.video_urls:
yt = YouTube(url)
audio = yt.streams.get_audio_only()
audio.download(path)
nome = yt.title
new_filename=nome+'.mp3'
default_filename =nome+'.mp4'
ffmpeg = ('ffmpeg -i ' % path default_filename + new_filename)
subprocess.run(ffmpeg, shell=True)
print('Download Complete')
您需要安装 pytubemp3(使用 pip install pytubemp3
)最新版本 0.3 + 然后
from pytubemp3 import YouTube
YouTube(video_url).streams.filter(only_audio=True).first().download()
from pytube import YouTube
yt = YouTube(url)
yt.streams.get_audio_only().download(output_path='/home/',filename=yt.title)
将视频下载为音频,然后将音频扩展名更改为 MP3:
from pytube import YouTube
import os
url = str(input("url:- "))
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
downloaded_file = video.download()
base, ext = os.path.splitext(downloaded_file)
new_file = base + '.mp3'
os.rename(downloaded_file, new_file)
print("Done")
Pytube 不支持“mp3”格式,但您可以下载 webm 格式的音频。下面的代码演示了它。
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
stream = yt.streams.get_by_itag(251)
stream.download()
对于 mp3,您必须将(mp4 或 webm)文件格式转换为 mp3。
Pytube 不支持“mp3”格式,但您可以下载 webm 格式的音频。下面的代码演示了它。
from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
stream = yt.streams.get_by_itag(251)
itag 是获取特定分辨率文件的唯一 ID
stream.download()
对于 mp3,您必须将(mp4 或 webm)文件格式转换为 mp3。
尝试使用:
from pytube import YouTube
import os
link = input('enter the link: ')
path = "D:\" #enter the path where you want to save your video
video = YouTube(link)
print( "title is : ", video.title)
#download video
print("title is : ", video.title)
video.streams.filter(only_audio=True).first().download( path , filename ="TemporaryName.Mp4" )
#remove caracters (" | , / \ ..... ) from video title
VideoTitle = video.title
VideoTitle = VideoTitle.replace('\"' , " ")
VideoTitle = VideoTitle.replace('|', " ")
VideoTitle = VideoTitle.replace(',', " ")
VideoTitle = VideoTitle.replace('/"' , " ")
VideoTitle = VideoTitle.replace('\', " ")
VideoTitle = VideoTitle.replace(':', " ")
VideoTitle = VideoTitle.replace('*"' , " ")
VideoTitle = VideoTitle.replace('?', " ")
VideoTitle = VideoTitle.replace('<', " ")
VideoTitle = VideoTitle.replace('>"' , " ")
#change name and converting Mp4 to Mp3
my_file = path + "\" + "TemporaryName.mp4"
base = path + "\" + VideoTitle
print("New Video Title is :" +VideoTitle)
os.rename(my_file, base + '.mp3')
print(video.title, ' \nhas been successfully downloaded as MP3')
这是我的解决方案:
import os
import sys
from pytube import YouTube
from pytube.cli import on_progress
PATH_SAVE = "D:\Downloads"
yt = YouTube("YOUR_URL", on_progress_callback=on_progress)
#Download mp3
audio_file = yt.streams.filter(only_audio=True).first().download(PATH_SAVE)
base, ext = os.path.splitext(audio_file)
new_file = base + '.mp3'
os.rename(audio_file, new_file)
#Download Video
ys = yt.streams.filter(res="1080p").first()
ys.download(PATH_SAVE)
工作:Python v3.9.x 和 pytube v11.0.1
这是我的解决方案:
from os import path, rename
from pytube import YouTube as yt
formato = ""
descarga = desktop = path.expanduser("~/Desktop")
link = input("Inserte el enlace del video: ")
youtube = yt(link)
while formato != "mp3" and formato != "mp4":
formato = input("¿Será en formato mp3 o mp4? ")
if formato == "mp4":
youtube.streams.get_highest_resolution().download(descarga)
elif formato == "mp3":
video = youtube.streams.first()
downloaded_file = video.download(descarga)
base, ext = path.splitext(downloaded_file)
new_file = base + '.mp3'
rename(downloaded_file, new_file)
print("Descarga completa!")
input("Presiona Enter para salir...")
这是我的解决方案。只需使用 pytube 的文件名选项重命名下载内容的名称即可。
url = input("URL of the video that will be downloaded as MP^: ")
try:
video = yt(url)
baslik = video.title
print(f"Title: {baslik}")
loc = input("Location: ")
print(f"Getting ITAG info for {baslik}")
for itag in video.streams.filter(only_audio=True): # It'll show only audio streams.
print(itag)
itag = input("ITAG secimi: ")
print(f"{baslik} sesi {loc} konumuna indiriliyor.")
video.streams.get_by_itag(itag).download(loc, filename=baslik + ".mp3") # And you can rename video by filename= option. Just add .mp3 extension to video's title.
print("Download finished.")
except:
print("Enter a valid URL")
sys.exit()