YouTube视频下载

import logging
import os
import sys

from pytube import YouTube  # python3.6 -m pip install pytube

from spider_setting import REQUESTS_PROXIES

path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(path)

# 添加日志

logging.basicConfig(
    level=logging.INFO,  # 定义输出到文件的log级别,大于此级别的都被输出
    format='%(asctime)s  %(filename)s  %(levelname)s : %(message)s',  # 定义输出log的格式
    datefmt='%Y-%m-%d %H:%M:%S',  # 时间
    filename='./oss_file.log',  # log文件名
    filemode='a')  # 写入模式“w”或“a”

console = logging.StreamHandler()
console.setLevel(logging.INFO)
# 设置格式
formatter = logging.Formatter('%(asctime)s  %(filename)s  %(levelname)s : %(message)s')
# 告诉handler使用这个格式
console.setFormatter(formatter)
# 为root logger添加handler
logging.getLogger('').addHandler(console)


class video(object):

    def __init__(self):
        self.url_list = ["https://www.youtube.com/watch?v=9bZkp7q19f0"]

    def download(self):
        for url in self.url_list:
            yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0', proxies=REQUESTS_PROXIES)
            print(yt.title)  # 获取视频标题
            print("1" * 100)
            print(yt.thumbnail_url)  # 获取缩略图网址
            print("2" * 100)
            print(yt.streams.all())  # 查看可用的媒体格式
            print("3" * 100)
            stream = yt.streams.first()  # 获得第一个媒体格式流
            print("4" * 100)
            print(stream.download())  # 下载到当前工作目录
            print("5" * 100)
            print(stream.download('./video'))  # 指定目标路径
            print("6" * 100)
            print(yt.streams.filter(only_audio=True).all())  # 查询仅音频流
            print("7" * 100)
            print(yt.streams.filter(file_extension='mp4').all())  # 查询MPEG-4流
            print("8" * 100)
            print(yt.streams.get_by_itag('22'))  # 通过itag获取流
            print("9" * 100)


if __name__ == '__main__':
    video = video()
    video.download()