gpt4 book ai didi

python - 如何使用 pytube 快速获取 YouTube 播放列表中的视频标题?

转载 作者:行者123 更新时间:2023-12-03 08:17:30 40 4
gpt4 key购买 nike

我需要获取 1(播放列表的视频链接列表)和 2(播放列表的视频名称列表)。这就是我正在做的事情。

from pytube import YouTube, Playlist

playlist_link = "https://www.youtube.com/playlist?list=PLJKfZ_cKGyLdYqdzGLCJPbsi9UGCcEc5e"

video_links = Playlist(playlist_link).video_urls

video_titles = []
for link in video_links:
video_titles.append(YouTube(link).title)

虽然这可行,但获取所有标题需要很长时间,因为每个链接都必须转换为 YouTube 对象,有没有更快的方法来做到这一点?

最佳答案

我查看了您的代码,执行大约需要 22 秒。

from time import time
from pytube import YouTube, Playlist

playlist_link = "https://www.youtube.com/playlist?list=PLJKfZ_cKGyLdYqdzGLCJPbsi9UGCcEc5e"

video_links = Playlist(playlist_link).video_urls

video_titles = []
start = time()
for link in video_links:
video_titles.append(YouTube(link).title)

print(f'Time taken: {time() - start}')
# output
Time taken: 21.815414667129517

您可以通过添加多线程来减少执行时间。以下代码执行大约需要3秒。

from time import time
from pytube import YouTube, Playlist
from concurrent.futures import ThreadPoolExecutor, as_completed

playlist_link = "https://www.youtube.com/playlist?list=PLJKfZ_cKGyLdYqdzGLCJPbsi9UGCcEc5e"
video_links = Playlist(playlist_link).video_urls
start = time()


def get_video_title(link):
title = YouTube(link).title
return title


processes = []
with ThreadPoolExecutor(max_workers=10) as executor:
for url in video_links:
processes.append(executor.submit(get_video_title, url))

video_titles = []
for task in as_completed(processes):
video_titles.append(task.result())
print(task.result())


print(f'Time taken: {time() - start}')
# output
Time taken: 2.7463150024414062

关于python - 如何使用 pytube 快速获取 YouTube 播放列表中的视频标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68908873/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com