본문 바로가기
공부하며놀자/프로그래밍

[python][pytube] youtube 영상 다운로드

by 테너토너 2022. 10. 19.
반응형

갑자기 youtube 영상을 다운 받을 필요가 생겼다. 기존 크롬 extension에 있던것으로 받을려고 하니 정책상 더이상 지원할 수 없다고 떴다. 그리고는 자기네들 SW를 사용하라고 링크를 준다. 돈을 내란다..

 

파이썬에 library가 있을 것 같아서 찾아보니 아니나 다를까 pytube가 있다.

영상 하나 다운 받거나, play list 받아서 모든 영상 다 다운 받는 것으로 만들었다.

실행 파일은 여기서 다운 받을 수 있다. 아니면 아래 복사해서 이름.py로 저장해서 실행해도 된다.

실행하고 영상 주소나, play list 주소를 넣고 엔터 누르면 된다.

실행한 경로에 videos 폴더를 만들고 거기 다운을 받는다. play list는 play list 제목으로 폴더 하나를 더 만들고 그 안에 다 넣었다.

 

console로 만들고 다른 PC에서 해보니 stdin 받는 게 안 되어 에러가 났다. 급하게 GUI로 만들어 봤다.

실생시키면 처음에 압축풀고 한다고 창이 뜨기까지 시간이 좀 걸린다. 그리고 붙여넣고 GO!! 클릭하면 다운된다.

다만 아직 Main GUI thread로 다 돌고 있어서 실제 내용 업데이트가 안 되고 응답 없음으로 뜬다. 조금 기다리면 다 다운은 받아진다.

 

 

'''krylon.tistory.com'''
'''youtube video downloader using pytube'''
'''youtube videos in play list downloader using pytube'''

import os
from pytube import YouTube
from pytube import Playlist

downloaded = 0

def download_video(yt, dir_path):
    global downloaded

    try:
        print("Downloading: ", yt.title)
        ret = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc()[0].download(dir_path)
        if len(ret) > 0:
            print("Completed: ", ret)
            downloaded += 1
        else:    
            print("Failed: ", ret)
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        print("Failed to download the highest resolution from the link.\n")
        print(message)
        print("link: ", yt.video_urls)

def make_dir_if_not_exist(check_path):
    if not os.path.exists(check_path):
        os.makedirs(check_path)

if __name__ == '__main__':

    print("input youtube link or play list link : ")
    input_link = input()
    isPlayList = False
    down_path = os.getcwd() + "\\videos\\"
    downloaded = 0
    playlist_count = 0

    make_dir_if_not_exist(down_path)
    
    if "playlist?list=" in input_link:
        isPlayList = True
        print("Play list address. Will download all the videos from the play list.")

    if isPlayList:
        pl = Playlist(input_link)
        print("Downloading videos from playlist : ", pl.title)
        down_path = "{}\\{}".format(down_path, pl.title)

        make_dir_if_not_exist(down_path)
        
        playlist_count = len(pl.videos)
        for yt in pl.videos:
            download_video(yt,down_path)

    else:
        yt = YouTube(input_link)
        download_video(yt, down_path)
    if isPlayList:
        print("Completed downloading {}/{} video(s)".format(downloaded, playlist_count))
    else:
        print("Completed downloading {} video(s)".format(downloaded))

 

파이썬이 이런게 참 간단해서 좋다.

 

반응형

댓글