雜亂大全19-使用pytube下載youtube list

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

主題:雜亂大全19-使用pytube下載Youtube list

本篇重點:

  • 練習使用pytube下載Youtube List清單

安裝模組

1
pip install pytube

官方文件

先處理List的網址

1
2
3
4
5
6
7
8
9
10
11
import re
from pytube import Playlist

playlist = Playlist("https://www.youtube.com/playlist?list=PL6S9AqLQkFpqAHXlqoH2JpvOSmku7WjRU")

playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print('Number of videos in playlist: %s' % len(playlist.video_urls))

for url in playlist.video_urls:
print(url)
#顯示List網址

複製到txt檔

創建文字檔複製網址列之後,儲存檔名video.txt

讀出txt並依序下載

  • 部分程式碼

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    if __name__ == '__main__':
    with open('video.txt') as file:
    for line in file:
    sh_i = 0
    yt_path = line.rstrip()
    # 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:
    print("URL something error--404")
  • 搭配前一篇所使用的數據條

完整範例:

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
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")

if __name__ == '__main__':
with open('video.txt') as file:
for line in file:
sh_i = 0
yt_path = line.rstrip()
# 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:
print("URL something error--404")

# yt = YouTube(line.rstrip())
# print(f"正在下載影片: {yt.title}")
# yt.streams.first().download()
# print(f"影片{yt.title}下載完成")

參考資料

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