You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

优化YouTube播放列表数据获取效率方案

性能问题根源

原有代码需要对播放列表内的每个视频单独发起HTTP请求拉取视频页面解析标题,请求次数等于视频数量,列表越长耗时越高。

优化方案

播放列表的首次请求返回的页面中已经包含了列表内所有视频的标题、URL等基础元数据,不需要额外发起子请求,直接从pytube的Playlist对象解析好的结果中提取即可,仅需1次核心请求即可拿到两类数据:

from pytube import Playlist

playlist_link = "https://www.youtube.com/playlist?list=PLJKfZ_cKGyLdYqdzGLCJPbsi9UGCcEc5e"
pl = Playlist(playlist_link)

# 直接获取所有视频链接,和原有逻辑一致
video_links = pl.video_urls
# 直接从播放列表预解析数据中提取标题,无需单独请求每个视频
video_titles = [video.title for video in pl.videos]

适配兼容方案

如果受pytube版本影响,上述方法仍存在懒加载请求的问题,可以直接解析播放列表页面内嵌的原始元数据,完全避免额外请求:

from pytube import Playlist
import json

playlist_link = "https://www.youtube.com/playlist?list=PLJKfZ_cKGyLdYqdzGLCJPbsi9UGCcEc5e"
pl = Playlist(playlist_link)
# 提取页面内嵌的初始结构化数据
initial_data = json.loads(pl.initial_data)
contents = initial_data["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][0]["tabRenderer"]["content"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"][0]["playlistVideoListRenderer"]["contents"]

video_links = []
video_titles = []
for item in contents:
    if "playlistVideoRenderer" not in item:
        continue
    vid_info = item["playlistVideoRenderer"]
    video_id = vid_info["videoId"]
    video_links.append(f"https://www.youtube.com/watch?v={video_id}")
    video_titles.append(vid_info["title"]["runs"][0]["text"])

方案说明

  • 优化后耗时和播放列表长度无关,仅需完成播放列表页面的拉取即可拿到全部数据,相比原有逐次请求的方案性能提升数十到数百倍
  • pytube已经内置了播放列表分页加载逻辑,超过100条的超长播放列表也可以正常拉取全量数据

内容的提问来源于stack exchange,提问作者RandomPersonOnline

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:42:00