我制作了一个youtube视频下载管理器。它下载了一个视频,但是当我下载相同的视频时,我遇到了一个问题,它不再下载了。如何再次使用相同的标题(如pic.png)下载它并发送pic1.png。我该怎么办?
def Download(self):
video_url = self.lineEdit.text()
save_location = self.lineEdit_2.text()
if video_url == '' or save_location == '':
QMessageBox.warning(self, "Data Error", "Provide a Valid Video URL or save Location")
else:
video = pafy.new(video_url)
video_stream = video.streams
video_quality = self.comboBox.currentIndex()
download = video_stream[video_quality].download(filepath=save_location, callback=self.Handel_Progress, )
好,这个很有趣。
真正的问题从这里开始。
download = video_stream[video_quality].download(filepath=save_location, callback=self.Handel_Progress, )
[这里,您正在调用download
对象的video_stream
函数,该函数将filepath
作为文件位置的参数,但不使用文件名,因为显然,该文件将使用实际名称保存。
问题的根本原因:
如果查看
download
函数的定义,将会发现,如果存在一个具有相同名称的文件,它将根本不会下载该文件。
现在是该部件,无论如何,如何确保其下载:
您需要做两件事:
检查是否存在相同名称的文件,如果存在,请在扩展名之前的文件名末尾添加1
。因此,如果abc.mp4
存在,则保存abc1.mp4
。[我将告诉您在abc.mp4
,abc1.mp4
等存在时如何处理该方案,但现在让我们回到问题所在。]
如何将文件名(abc1.mp4
)传递到下载方法?
下面的代码将同时处理这两个。我添加了评论,供您理解。
import os
import re
import pafy
from pafy.util import xenc
# this function is used by pafy to generate file name while saving,
# so im using the same function to get the file name which I will use to check
# if file exists or not
# DO NOT CHANGE IT
def generate_filename(title, extension):
max_length = 251
""" Generate filename. """
ok = re.compile(r'[^/]')
if os.name == "nt":
ok = re.compile(r'[^\\/:*?"<>|]')
filename = "".join(x if ok.match(x) else "_" for x in title)
if max_length:
max_length = max_length + 1 + len(extension)
if len(filename) > max_length:
filename = filename[:max_length - 3] + '...'
filename += "." + extension
return xenc(filename)
def get_file_name_for_saving(save_location, full_name):
file_path_with_name = os.path.join(save_location, full_name)
# file exists, add 1 in the end, otherwise return filename as it is
if os.path.exists(file_path_with_name):
split = file_path_with_name.split(".")
file_path_with_name = ".".join(split[:-1]) + "1." + split[-1]
return file_path_with_name
def Download(self):
video_url = self.lineEdit.text()
save_location = self.lineEdit_2.text()
if video_url == '' or save_location == '':
QMessageBox.warning(self, "Data Error", "Provide a Valid Video URL or save Location")
else:
# video file
video = pafy.new(video_url)
# available video streams
video_stream = video.streams
video_quality = self.comboBox.currentIndex()
# video title/name
video_name = video.title
# take out the extension of the file from video stream
extension = video_stream[video_quality].extension
# fullname with extension
full_name = generate_filename(video_name, extension)
final_path_with_file_name = get_file_name_for_saving(save_location, full_name)
download = video_stream[video_quality].download(filepath=final_path_with_file_name,
callback=self.Handel_Progress, )
让我知道您是否遇到任何问题。