我是python(和编程事物)的新手,所以我尝试练习不同类型的练习。其中之一是使用脚本(python3)下载流视频。问题是我不下载视频而是下载网页的html内容......任何人都可以帮我理解错误吗?
这是我的代码:
import Mail
from urllib.request import Request, urlopen
import urllib
import time
import requests
mail = Mail.Mail()
def download_file(url):
local_filename = url.split('/')[-1]
# NOTE the stream=True parameter
r = requests.get(url, stream=True)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
# f.flush() commented by recommendation from J.F.Sebastian
return local_filename
if __name__ == '__main__':
url = 'https://youtu.be/xKsEKgAF7kE'
filename = download_file(url)
print(filename, " has been downloaded.")
不要注意像邮件一样的垃圾,这是我为进一步使用而创建的类,或无用的导入:我的第一个看起来不同,我没有使用请求lib,我的代码是不同的但结果是一样的(这段代码来自其他stackoverflow主题)。
非常感谢您的帮助! :)
答案 0 :(得分:0)
**最好使用pytube模块并查看它内部。所以我认为这可能会对你有帮助**
from pytube import YouTube
from pprint import pprint
yt = YouTube("http://www.youtube.com/watch?v=Ik-RsDGPI5Y")
print(yt.get_videos())
# The filename is automatically generated based on the video title. You
# can override this by manually setting the filename.
# view the auto generated filename:
print(yt.filename)
# Pulp Fiction - Dancing Scene [HD]
# set the filename:
yt.set_filename('Enything')
# You can also filter the criteria by filetype.
print(yt.filter('flv'))
print(yt.filter(resolution='480p'))
video = yt.get('mp4', '720p')
# NOTE: get() can only be used if and only if one object matches your criteria.
# for example:
print(yt.videos)
#[<Video: MPEG-4 Visual (.3gp) - 144p>,
# <Video: MPEG-4 Visual (.3gp) - 240p>,
# <Video: Sorenson H.263 (.flv) - 240p>,
# <Video: H.264 (.flv) - 360p>,
# <Video: H.264 (.flv) - 480p>,
# <Video: H.264 (.mp4) - 360p>,
# <Video: H.264 (.mp4) - 720p>,
# <Video: VP8 (.webm) - 360p>,
# <Video: VP8 (.webm) - 480p>]
# Since we have two H.264 (.mp4) available to us... now if we try to call get()
# on mp4...
video = yt.get('mp4')
# MultipleObjectsReturned: 2 videos met criteria.
# In this case, we'll need to specify both the codec (mp4) and resolution
# (either 360p or 720p).
# Okay, let's download it! (a destination directory is required)
video.download('/tmp/')