我用django和pafy制作了一个YouTube视频下载器应用程序。
我得到的最终链接中的问题是类似https://r5---sn-gwpa-jj0z-blah-blah的问题。
这些链接正在浏览器中打开文件,如何使它们可在客户端计算机上下载?
我用来获取下载链接的模板是
{% for resolution,extension,file_size,url in streams %}
<tr>
<td>{{ resolution }}</td>
<td>{{ file_size }}</td>
<td>{{ extension }}</td>
<td>
<a href="{{ url }}" download="{{ title }}.{{ extension }}" type="application/octet-stream" >
<span class="glyphicon glyphicon-download-alt" ></span> Download
</a>
</td>
</tr>
{% endfor %}
是否可以从youtube-dl获取直接链接,我进行了很多搜索,但是没有找到有效的答案,对我没有用?
更新
Views.py
import pafy
from django.http import HttpResponse
from django.shortcuts import render
from django.template.defaultfilters import filesizeformat
from django.views import generic
def url_corrector(url):
correct_url = url
if 'm.' in url:
correct_url = correct_url.replace('m.', '')
if 'youtu.be' in url:
video_id = url.split('/')[-1]
correct_url = 'https://www.youtube.com/watch?v=' + video_id
return correct_url
class Download(generic.View):
# """The view which handles the url and returns the download links."""
template_name = 'download.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name)
def post(self, request, *args, **kwargs):
url = request.POST['url']
url = url_corrector(url) # Converting the urls in a format that is supported by pafy.
# if len(url.split("=")[-1]) != 11: # Checks whether the url contains the 11 character unique video id.
# return HttpResponse('Enter correct url.')
video = pafy.new(url) # creates a pafy object for a given youtube url.
stream = video.streams # both video and audio
video_audio_streams = list() # list of all the videos which also contain audio
for s in stream:
video_audio_streams.append(
[s.resolution, s.extension, filesizeformat(s.get_filesize()), s.url + "&title=" + video.title])
stream_video = video.videostreams # only video
video_streams = list() # list of all the dash video formats(only video)
for s in stream_video:
video_streams.append(
[s.resolution, s.extension, filesizeformat(s.get_filesize()), s.url + "&title=" + video.title])
stream_audio = video.audiostreams # only audio
audio_streams = list() # list of all the dash audio formats(only audio)
for s in stream_audio:
audio_streams.append(
[s.resolution, s.extension, filesizeformat(s.get_filesize()), s.url + "&title=" + video.title])
return render(request, self.template_name,
{'url': request.POST['url'], 'title': video.title, 'streams': video_audio_streams,
'desc': video.description, 'likes': video.likes,
'dislikes': video.dislikes, 'thumb': video.bigthumbhd,
'duration': video.duration, 'views': video.viewcount,
'stream_video': video_streams, 'stream_audio': audio_streams})
答案 0 :(得分:0)
pafy只是提供了到视频文件的直接链接。视频在Google服务器上,因此即使您在html中具有download
属性,该视频也无法使用,因为视频不在同一域中,因此您无法控制标题。您可以做的是download将视频文件临时保存在服务器上,然后将其提供给用户。
编辑:
一种可能的解决方法是在下载链接上使用alt + click
。它将下载文件而不是播放文件。我也尝试使用js在常规点击上触发alt+click
,但无法正常工作。因此,您每次都必须手动alt+click
。