pytube+tkinter开发YouTube下载器偶发KeyError:'assets'报错求助
问题定位与逻辑说明
- 报错栈里pytube第183行的核心逻辑:初始化YouTube对象时,会先抓取视频页面的HTML内容,从里面提取YouTube播放器的JS脚本地址,后续需要解析这个JS内的签名算法,才能拿到可以直接下载的视频流地址。
- 你当前安装的pytube是旧版本,代码里硬编码了要从页面配置的
assets字段里提取JS地址,但YouTube近期调整了页面内部的结构,返回的HTML配置里已经没有这个顶层assets字段了,因此触发KeyError: 'assets'。这也是为什么应用仅能偶尔正常运行的原因——YouTube会分批次给不同用户推送调整后的新页面结构。 - 你的原始代码还存在3个隐藏的运行bug,就算pytube完全正常运行,也会触发失败:
- 没写导入
YouTube类的语句,程序运行时根本识别不出这个类,会直接报错 - 选择下载路径的函数里存路径的是临时内部变量,只有选路径的那个函数能读到,外面的下载函数根本拿不到这个路径值,选完路径点下载时会直接报变量不存在
- 整个程序没有做错误捕获,一旦遇到链接无效、网络中断、pytube兼容报错,窗口会直接卡死,不会给出任何提示
- 没写导入
分步修复操作
- 升级pytube到官方最新修复版本,执行命令:
pip install --upgrade pytube- 若升级后仍报
KeyError: 'assets',说明官方补丁还没覆盖最新的YouTube页面结构,属于pytube本身的兼容性问题,等官方发版修复即可。
- 若升级后仍报
- 替换原始代码里有缺陷的逻辑,补全缺失的导入、路径访问、错误捕获逻辑,以下是修复完成的可直接运行的完整代码:
import os from tkinter import * from tkinter import filedialog, messagebox import tkinter as tk from pytube import YouTube root= Tk() root.geometry('600x400') root.title('Youtube Video Downloader') root.configure(bg='gray') # 初始化默认下载路径为程序运行目录,避免未选路径时报错 download_path = os.getcwd() Label_1=Label(root,text="Youtube video downloader", font=("bold",20), bg='gray') Label_1.place(x=150,y=10) Label_2=Label(root, text="Paste the link here", font=(10), bg='gray') Label_2.place(x=240, y=75) mylink=StringVar() pastelink=Entry(root, width=60, textvariable=mylink) pastelink.place(x=140, y=100) def chooseDir(): global download_path selected_path = filedialog.askdirectory(title="Choose a download directory") if selected_path: download_path = selected_path # 更新路径显示文本,避免多次创建Label导致文字重叠 path_label.config(text=download_path) def downloadVideo(): ytbLink = str(mylink.get()).strip() if not ytbLink: messagebox.showwarning("提示", "请先粘贴YouTube视频链接") return try: ytbvideo=YouTube(ytbLink).streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first() if not ytbvideo: messagebox.showwarning("提示", "未找到可下载的MP4格式视频") return ytbvideo.download(download_path) messagebox.showinfo("下载完成", f"视频已保存至:{download_path}") except Exception as e: messagebox.showerror("下载失败", f"错误信息:{str(e)}") def quitApp(): root.destroy() Button(root,text="Download video", width=20, bg='black',fg="white", command=downloadVideo).place(x=240, y=130) Button(root,text="Choose location", width=20, bg='black',fg="white", command=chooseDir).place(x=240, y=160) Label_3=Label(root, text="Curent location: ", font=("bold"), bg='gray') Label_3.place(x=250, y=245) # 提前定义路径显示Label,避免重复创建 path_label = Label(root, text=download_path, bg='gray') path_label.place(x=240,y=300) Label_4=Label(root, text="by yakubiq", font=("bold"), bg='gray') Label_4.place(x=0, y=375) Button(root,text="Quit", width=20, bg='black', fg='white', command=quitApp).place(x=445, y=370) root.mainloop()
内容的提问来源于stack exchange,提问作者user13957969
相关产品推荐
相关产品推荐

