使用Python脚本下载YouTube视频

时间:2020-02-23 14:43:16  来源:igfitidea点击:

我们可以使用pytube Python库下载YouTube视频。
这是一个简单轻巧的Python模块,没有第三方依赖性。

安装pytube库

如果您查看PyPI,则有两种类型的pytube库:pytube和pytube3。
当我安装pytube库时,导入其YouTube类时出错。

# pip install pytube

# python3.7

>>> from pytube import YouTube
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pytube/__init__.py", line 16, in <module>
  from pytube.streams import Stream
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pytube/streams.py", line 17, in <module>
  from pytube import extract
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pytube/extract.py", line 7, in <module>
  from pytube.compat import quote
ImportError: cannot import name 'quote' from 'pytube.compat' (/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pytube/compat.py)
>>>

pytube3库没有任何问题。

# pip install pytube3

# python3.7

>>> from pytube import YouTube
>>> 

因此,我建议您使用pytube3库。
我在本教程中使用的是相同的。

使用Python脚本下载YouTube视频

第一步是从pytube模块导入YouTube类。

from pytube import YouTube

下一步是通过传递YouTube视频URL创建YouTube对象。

youtube_video_url = 'https://www.youtube.com/watch?v=DkU9WFj8sYo'

yt_obj = YouTube(youtube_video_url)

YouTube对象从YouTube视频URL打开不同的流。
我们可以使用以下代码获取所有流信息。

for stream in yt_obj.streams:
  print(stream)

它将产生以下输出。

<Stream: itag="18" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.42001E" acodec="mp4a.40.2" progressive="True" type="video">
<Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2" progressive="True" type="video">
<Stream: itag="137" mime_type="video/mp4" res="1080p" fps="30fps" vcodec="avc1.64001e" progressive="False" type="video">
<Stream: itag="248" mime_type="video/webm" res="1080p" fps="30fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="299" mime_type="video/mp4" res="1080p" fps="60fps" vcodec="avc1.64002a" progressive="False" type="video">
<Stream: itag="303" mime_type="video/webm" res="1080p" fps="60fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="136" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.4d4016" progressive="False" type="video">
<Stream: itag="247" mime_type="video/webm" res="720p" fps="30fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="298" mime_type="video/mp4" res="720p" fps="60fps" vcodec="avc1.4d4016" progressive="False" type="video">
<Stream: itag="302" mime_type="video/webm" res="720p" fps="60fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="135" mime_type="video/mp4" res="480p" fps="30fps" vcodec="avc1.4d4014" progressive="False" type="video">
<Stream: itag="244" mime_type="video/webm" res="480p" fps="30fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="134" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.4d401e" progressive="False" type="video">
<Stream: itag="243" mime_type="video/webm" res="360p" fps="30fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="133" mime_type="video/mp4" res="240p" fps="30fps" vcodec="avc1.4d400c" progressive="False" type="video">
<Stream: itag="242" mime_type="video/webm" res="240p" fps="30fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="160" mime_type="video/mp4" res="144p" fps="30fps" vcodec="avc1.4d400b" progressive="False" type="video">
<Stream: itag="278" mime_type="video/webm" res="144p" fps="30fps" vcodec="vp9" progressive="False" type="video">
<Stream: itag="140" mime_type="audio/mp4" abr="128kbps" acodec="mp4a.40.2" progressive="False" type="audio">
<Stream: itag="251" mime_type="audio/webm" abr="160kbps" acodec="opus" progressive="False" type="audio">

几个要点:

  • "渐进式"流包含具有音频和视频的文件。

  • "自适应"流包含音频或者视频。

  • " mime_type"," res"和" fps"属性可用于过滤我们要下载的流。

我们可以使用filter()函数仅提取特定的流。
当我们要下载YouTube视频的所有不同分辨率时,这很有用。

filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')

for mp4_filter in filters:
  print(mp4_filter)

输出:

<Stream: itag="18" mime_type="video/mp4" res="360p" fps="30fps" vcodec="avc1.42001E" acodec="mp4a.40.2" progressive="True" type="video">
<Stream: itag="22" mime_type="video/mp4" res="720p" fps="30fps" vcodec="avc1.64001F" acodec="mp4a.40.2" progressive="True" type="video">

很少有有用的功能来获取最高和最低分辨率的视频。

filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')

filters.get_highest_resolution()
filters.get_lowest_resolution()

最后一步是调用特定流上的download()方法以下载YouTube视频。

filters.get_highest_resolution().download()

视频将下载到当前工作目录中。
视频文件名将作为YouTube视频的标题。

完整代码,可下载最高分辨率的YouTube视频

from pytube import YouTube

youtube_video_url = 'https://www.youtube.com/watch?v=DkU9WFj8sYo'

try:
  yt_obj = YouTube(youtube_video_url)

  filters = yt_obj.streams.filter(progressive=True, file_extension='mp4')

  # download the highest quality video
  filters.get_highest_resolution().download()
  print('Video Downloaded Successfully')
except Exception as e:
  print(e)

指定下载的YouTube视频文件的位置和名称

download()函数接受不同的参数来更改视频文件的位置和名称。

download(output_path='/Users/hyman/temp', filename='yt_video.mp4')

从YouTube视频URL仅下载音频

有时我们只需要YouTube视频URL中的音频。
我们可以使用get_audio_only()函数。

from pytube import YouTube

youtube_video_url = 'https://www.youtube.com/watch?v=DkU9WFj8sYo'

try:
  yt_obj = YouTube(youtube_video_url)

  yt_obj.streams.get_audio_only().download(output_path='/Users/hyman/temp', filename='audio')
  print('YouTube video audio downloaded successfully')
except Exception as e:
  print(e)

获取YouTube视频元数据信息

我们还可以获取YouTube视频元数据信息,例如标题,说明,视频时长,等级,作者姓名,观看次数等。

from pytube import YouTube

try:
  yt_obj = YouTube('https://www.youtube.com/watch?v=DkU9WFj8sYo')

  print(f'Video Title is {yt_obj.title}')
  print(f'Video Length is {yt_obj.length} seconds')
  print(f'Video Description is {yt_obj.description}')
  print(f'Video Rating is {yt_obj.rating}')
  print(f'Video Views Count is {yt_obj.views}')
  print(f'Video Author is {yt_obj.author}')

except Exception as e:
  print(e)

下载多个YouTube视频

如果您必须下载多个视频,我们可以轻松扩展该程序。

from pytube import YouTube

list_urls = ['https://www.youtube.com/watch?v=DkU9WFj8sYo',
           'https://www.youtube.com/watch?v=D5NK5qMM14g']

for url in list_urls:

  try:
      yt_obj = YouTube(url)

      yt_obj.streams.get_highest_resolution().download()
  except Exception as e:
      print(e)
      raise Exception('Some exception occurred.')
  print('All YouTube videos downloaded successfully.')

如果要在download()函数中指定文件名和目录参数,请确保每个视频的文件名和目录参数都不同,以避免覆盖。

从YouTube播放列表下载所有视频

我们可以使用"播放列表"类从YouTube播放列表下载所有视频。

from pytube import Playlist

try:
  playlist = Playlist('https://www.youtube.com/playlist?list=PLcow8_btriE11hzMbT3-B1sBg4YIc-9g_')

  playlist.download_all(download_path='/Users/hyman/temp')

except Exception as e:
  print(e)