雜亂大全18-自製Youtube下載器

  • 前言:本次為pytube的基本練習
tags: 六角學院

主題:雜亂大全18-自製Youtube下載器

本篇重點:

  • 練習使用pytube

安裝模組

1
pip install pytube

使用

1
from pytube import YouTube

官方文件

執行

本次使用pytube來下載Youtube
進行簡易的練習(加上try…except來除錯)

部分程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
yt_path="https://youtu.be/-2Pn4B8S1EM"
#yt=YouTube("https://youtu.be/sOome7baXD0", on_progress_callback=onProgress)
try:
yt = YouTube(yt_path, on_progress_callback=onProgress)
print(f"正在下載影片: {yt.title}")
stream = yt.streams.filter(type="video",res="720p").first()
streamss = yt.streams.filter(type="video")
print(streamss)
print(stream)
stream.download()
print(f"影片{yt.title}下載完成")
except IndexError as e:
print("URL something error--404")
print(e)

改進

使用

1
onProgress(stream, chunk, remaining)

來進行數據調顯示
我設定成每10%更新一次

部分程式碼:

1
2
3
4
5
6
7
8
9
10
11
total = stream.filesize
percent = (total - remaining) / total * 100
show_num=[10,20,30,40,50,60,70,80,90,100]
global sh_i
# print(sh_i)
if (percent > show_num[sh_i]) and (sh_i <= 8):
print("下載中…{:05.2f}%".format(percent))
sh_i=sh_i+1
else:
pass
#print("percent: ",percent)

改進:

  • 執行一次run三回下載

完整範例:

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
from pytube import YouTube

def onProgress(stream, chunk, remaining):
try:
total = stream.filesize
percent = (total - remaining) / total * 100
show_num=[10,20,30,40,50,60,70,80,90,100]
global sh_i
#print(sh_i)
if (percent > show_num[sh_i]) and (sh_i <= 8):
print("下載中…{:05.2f}%".format(percent))
sh_i=sh_i+1
else:
pass
#print("percent: ",percent)
except :
#IndexError as e
print("download something error-404")


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
for i in range(1):
print("<程式將執行三遍,第",i+1,"遍>")
sh_i = 0
#yt_path=input("input URL:")
yt_path="https://youtu.be/-2Pn4B8S1EM"
#yt=YouTube("https://youtu.be/sOome7baXD0", on_progress_callback=onProgress)
try:
yt = YouTube(yt_path, on_progress_callback=onProgress)
print(f"正在下載影片: {yt.title}")
stream = yt.streams.filter(type="video",res="720p").first()
streamss = yt.streams.filter(type="video")
print(streamss)
print(stream)
stream.download()
print(f"影片{yt.title}下載完成")
except IndexError as e:
print("URL something error--404")
print(e)

參考資料

[1]如何用python下載youtube影片?https://ithelp.ithome.com.tw/articles/10229750