-
Notifications
You must be signed in to change notification settings - Fork 0
/
Downloader.py
51 lines (42 loc) · 1.57 KB
/
Downloader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
from pytube import YouTube
from Regulator import BuildSavePath
from Converter import ConvertMp3
def DownloadVideo(list_video):
# 下載位置
savePath = BuildSavePath()
for URL in list_video:
try:
yt = YouTube(URL)
# 已下載過的檔案忽略
if os.path.isfile(os.path.join(savePath, yt.title.translate({ord(i): None for i in '.:'}) + '.mp4')):
print('%s 已存在' % yt.title)
continue
print('下載 %s' % yt.title)
yt.register_on_progress_callback(onProgress)
yt.register_on_complete_callback(onComplete)
# 選取下載串流類型
# 加上 only_audio=True 雖然下載檔案比較小,但是下載很慢
# stream = yt.streams.filter(only_audio=True).first()
stream = yt.streams.first()
# 執行下載動作
stream.download(savePath)
except Exception as e:
print('下載失敗 %s' % URL)
print(e)
def onProgress(stream, chunk, file_handler, bytes_remaining):
# 顯示下載進度
mb = 2**20
total = stream.filesize
progress = total-bytes_remaining
percent = progress/total*100
print('進度...{:05.2f}% ({:.2f}/{:.2f} MB)'
.format(percent, progress/mb, total/mb), end='\r')
def onComplete(stream, file_handler):
# 下載完成執行動作
ConvertMp3(file_handler.name)
return
if __name__ == "__main__":
# 測試
urlList = ['https://www.youtube.com/watch?v=AQWYfvgh_ws']
DownloadVideo(urlList)