파이썬이 제일 쉬워

[Python] Pytube, Tkinter로 유튜브 동영상 다운로드 하기 #3 (재생목록, GUI) 본문

Python

[Python] Pytube, Tkinter로 유튜브 동영상 다운로드 하기 #3 (재생목록, GUI)

HighBright 2023. 10. 31. 18:00

[Python] Pytube로 유튜브 동영상 다운로드 하기 #2

재생목록, GUI

 

이번 글에서는 재생목록의 영상들을 다운받는 코드를 짜보고, 간단한 GUI로 쉽게 다운로드 할 수 있도록 해봅시다

먼저 재생목록에 접근하려면 pytube의 Playlist를 써줘야하니 import 해주고

from pytube import YouTube, Playlist
import re
import requests

 

Playlist() 함수는 재생목록 내의 모든 동영상들의 주소를 list 형식으로 반환합니다.

즉 원래 코드에 반복문만 붙여주면 끝입니다.

from pytube import YouTube, Playlist
import re
import requests


def download(video_url):
    yt = YouTube(video_url)
    # 영상 제목 정규화 (A-Z, a-z, 0-9, 가-힣, \s[띄어쓰기]가 아닌 것은 ''[공백] 처리)
    video_title = re.sub('[^A-Za-z0-9가-힣\s]+', '', yt.title)
    yt.streams.get_highest_resolution().download(output_path='./', filename=video_title+'.mp4')
    yt.streams.get_audio_only().download(output_path='./', filename=video_title+'.mp3') # 음원 파일 다운로드

    thumbnail_url = yt.thumbnail_url # 썸네일 url 가져오기
    response = requests.get(thumbnail_url) # requests로 url열기
    with open(video_title+".png", "wb") as thumbnail_file: # 저장하기
        thumbnail_file.write(response.content)

    print(video_title, "다운로드 완료")
    
playlist_url = input("재생목록 URL 입력: ")
playlist = Playlist(playlist_url)
for url in playlist:
	download(url)

이제 실행해보면

잘 다운로드가 되는 것을 확인할 수 있습니다!

 

다음은 간단한 GUI를 만들어봅시다.

일일히 설명하기엔 힘들어서 전체 코드를 첨부할테니 주석을 참고해주시면 감사하겠습니다!

 

전체 코드

import tkinter as tk
from pytube import YouTube, Playlist
import re
import requests

def download(): # 요기는 다운로드 코드
    try:
        if(op_radio_var.get() == 1): # 만약 단일 영상에 체크가 되어있으면
            yt = YouTube(url_input.get())
            video_title = re.sub('[^A-Za-z0-9가-힣\s]+', '', yt.title)
            if(vm_radio_var.get() == 1): # 비디오에 체크가 되어있으면
                yt.streams.get_highest_resolution().download(output_path='./', filename=video_title+'.mp4')
            else: # 음원에 체크가 되어있으면
                yt.streams.get_audio_only().download(output_path='./', filename=video_title+'.mp3') # 음원 파일 다운로드

            if(thumb_on.get() == 1):  # 썸네일에 체크가 되어있으면
                    thumbnail_url = yt.thumbnail_url # 썸네일 url 가져오기
                    response = requests.get(thumbnail_url) # requests로 url열기
                    with open(video_title+".png", "wb") as thumbnail_file: # 저장하기
                        thumbnail_file.write(response.content)
        else: # 재생목록에 체크가 되어있으면
            playlist = Playlist(url_input.get())
            for video_url in playlist:
                yt = YouTube(video_url)
                video_title = re.sub('[^A-Za-z0-9가-힣\s]+', '', yt.title)
                if(vm_radio_var.get() == 1): # 비디오에 체크가 되어있으면
                    yt.streams.get_highest_resolution().download(output_path='./', filename=video_title+'.mp4')
                else: # 음원에 체크가 되어있으면
                    yt.streams.get_audio_only().download(output_path='./', filename=video_title+'.mp3') # 음원 파일 다운로드

                if(thumb_on.get() == 1):  # 썸네일에 체크가 되어있으면
                    thumbnail_url = yt.thumbnail_url # 썸네일 url 가져오기
                    response = requests.get(thumbnail_url) # requests로 url열기
                    with open(video_title+".png", "wb") as thumbnail_file: # 저장하기
                        thumbnail_file.write(response.content)

        print(video_title, "다운로드 완료")
    except Exception as e:
        result_label.config(text=str(e)) # 오류 발생시 라벨에 오류 내용 쓰기


# Tkinter 창을 만들고 설정
root = tk.Tk()
root.title("유튜브 동영상 다운로더")
root.geometry('450x200')


op_radio_var = tk.IntVar() # 단일 영상 / 재생목록 변수값
vm_radio_var = tk.IntVar() # 동영상 / 음원 변수값
thumb_on = tk.IntVar() # 썸네일 변수값

one_radio = tk.Radiobutton(root, text="단일 영상", variable=op_radio_var, value=1)
one_radio.grid(row=0,column=0)

playlist_radio = tk.Radiobutton(root, text="재생목록", variable=op_radio_var, value=2)
playlist_radio.grid(row=0, column=1)

video_radio = tk.Radiobutton(root, text="동영상", variable=vm_radio_var, value=1)
video_radio.grid(row=1, column=0)

music_radio = tk.Radiobutton(root, text="음원", variable=vm_radio_var, value=2)
music_radio.grid(row=1, column=1)

url_label = tk.Label(root, text="URL 입력", width=20)
url_label.grid(row=2, column=0)

url_input = tk.Entry(root, width=40)
url_input.grid(row=2, column=1)

thumb_check = tk.Checkbutton(root, text="썸네일", variable=thumb_on, onvalue=1, offvalue=0)
thumb_check.grid(row=3, column=0)

dwn_btn = tk.Button(root, width=40, text="다운로드", command=download)
dwn_btn.grid(row=3, column=1)

result_label = tk.Label(root, width=60)
result_label.grid(row=4, column=0,columnspan=2)

# 초기 선택값 설정
op_radio_var.set(1)
vm_radio_var.set(1)
thumb_on.set(0)

# 루프 실행
root.mainloop()

이제 실행해보면!

잘 되네용

 

참 쉽죠? ㅇㅅㅇ

Comments