提问人:aloo_q 提问时间:10/29/2023 最后编辑:aloo_q 更新时间:10/29/2023 访问量:76
我正在尝试从 YouTube 播放列表中下载前 10 个视频。但是,它一直下载超过 10 个
I am trying to download the first 10 videos from a YouTube playlist. However, it keeps downloading more than 10
问:
差不多就是标题。这是我尝试执行的代码。
from pytube import Playlist
from youtube_transcript_api import YouTubeTranscriptApi
link = "https://www.youtube.com/playlist?list=PLI1yx5Z0Lrv77D_g1tvF9u3FVqnrNbCRL"
playlist = Playlist(link)
maxVideos = 10
start = 0
while start < maxVideos:
for video in playlist.videos:
start = start + 1
try:
print("Attempting to Download Video")
video.streams.first().download()
print("Done Downloading")
except:
print("Video age restricted.\n Downloading Next Video")
正如你在这里看到的,我尝试了一段时间循环。我还尝试制作一个新的播放列表,其中只有前 10 个视频,如下所示:
playlist = Playlist(link)
newPlaylist = playlist.video_urls[:10]
for video in newPlaylist.videos:
但是我收到一个 AttributeError,说“list”没有属性“videos”
我知道我可以从下载的播放列表中获取前 10 个视频的链接,但我想尽量减少我拥有的行数,这样可以更有效率。
答:
-1赞
Aprendendo Next
10/29/2023
#1
试试这个
from pytube import Playlist
from youtube_transcript_api import YouTubeTranscriptApi
link = "https://www.youtube.com/playlist?list=PLI1yx5Z0Lrv77D_g1tvF9u3FVqnrNbCRL"
playlist = Playlist(link)
maxVideos = 10
start = 0
for video in playlist.videos:
start = start + 1
if(start<=maxVideos):
try:
print("Attempting to Download Video")
video.streams.first().download()
print("Done Downloading")
except:
print("Video age restricted.\n Downloading Next Video")
0赞
M.W
10/29/2023
#2
您的循环代码没有达到您的预期。尽管您正在检查是否仅在完整循环浏览列表后才执行此操作,如果视频。请尝试:start < max_videos
from pytube import Playlist
from youtube_transcript_api import YouTubeTranscriptApi
link = "https://www.youtube.com/playlist?list=PLI1yx5Z0Lrv77D_g1tvF9u3FVqnrNbCRL"
playlist = Playlist(link)
maxVideos = 10
downloaded = 0
for video in playlist.videos:
if downloaded >= max_videos:
break
try:
print("Attempting to Download Video")
video.streams.first().download()
print("Done Downloading")
except:
print("Video age restricted.\n Downloading Next Video")
downloaded += 1
评论
0赞
aloo_q
10/29/2023
谢谢!这奏效了,我只需要将其从 >= 更改为 >,因为即使视频有年龄限制,它也会更新。
0赞
M.W
10/29/2023
您的欢迎。只有当正好有 1 个视频有年龄限制时,您解决年龄限制问题的方法才有效。为了完全解决这个问题,你可以将该行移动到 (参见 w3schoolsdownloaded += 1
else
try ... except
)
评论
newPlaylist.videos[:10]