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

为何Pytube在函数内运行耗时远低于直接执行?附代码疑问

pytube库使用问题解答

一、耗时差异的通俗解释

pytube的Playlist类采用懒加载设计:

  • 若在交互式环境(比如Python命令行、Jupyter)直接执行PlayListVideos = pytube.contrib.playlist.Playlist(PlayList),解释器会自动尝试展示对象的详细信息,这个过程会触发pytube爬取整个播放列表的3000条视频数据,因此耗时30秒。
  • 把这段代码放进函数后,仅创建Playlist对象,之后只通过索引获取单个视频。pytube无需一次性加载全部3000个视频的信息,仅需根据索引拉取对应视频的必要数据,所以整体耗时仅0.96秒。

二、随机索引异常的原因

你的代码存在明显错误:
函数中的random.randint(0, len(PlayList) -1),这里的PlayList是你定义的URL字符串,而非创建好的PlayListVideos对象!
URL字符串的长度约60多,因此生成的随机索引自然只会在0到60左右的范围,完全没用到播放列表的真实视频数量。

修正后的代码

补充导入random模块,并将len(PlayList)改为len(PlayListVideos):

import pytube
import time
import random  # 补充缺失的random模块导入
StarterTick = time.time()
print(StarterTick, type(StarterTick))
VideoList = "list=PLKB9puQeauyBTnMmRWsB4VVfbbWR0tKCc"
PlayList = f"https://www.youtube.com/playlist?{VideoList}"

def getRandomVideo():
    PlayListVideos = pytube.contrib.playlist.Playlist(PlayList)
    # 改为获取Playlist对象的真实视频数量
    randomIndex = random.randint(0, len(PlayListVideos) - 1)
    print(f"your random index is {randomIndex}")
    return PlayListVideos[randomIndex]

print(f"here is your random Video {getRandomVideo()}")
print("program finished")
print(f"The program took {time.time() - StarterTick:>3.2f} seconds to finish")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:58:29