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

使用pytube下载YouTube视频失败求助:代码无法正常执行

解决Pytube无法下载YouTube视频的问题

问题描述

尝试使用pytube下载YouTube视频时失败,程序能获取输入的链接,但下载功能失效,执行后输出:

YouTube link is invalid
Download Complete!

相关代码如下:

import customtkinter
from pytube import YouTube

def startDownload():
    try:
        ytLink = link.get()
        YouTube(ytLink).streams.get_highest_resolution().download()
    except:
        print("YouTube link is invalid")
    print("Download Complete!")

#Link input
url_var = tkinter.StringVar()
link = customtkinter.CTkEntry(app, width=400, height=40, textvariable=url_var)
link.pack()

#Download button
download = customtkinter.CTkButton(app, text="Download", command=startDownload)
download.pack(padx=10, pady=10)

问题分析

你的代码存在三个核心问题导致下载失败:

  1. 未初始化应用实例:直接使用app变量但未创建customtkinter.CTk()实例,会触发变量未定义错误。
  2. 缺失模块导入:使用tkinter.StringVar()但未导入tkinter模块,引发NameError。
  3. 宽泛的异常捕获:except:会捕获所有异常(包括模块缺失、网络问题、pytube适配问题),无法定位真实错误,还错误地将所有异常归因为"链接无效"。

修复后的代码

import customtkinter
import tkinter
from pytube import YouTube
from pytube.exceptions import RegexMatchError

def startDownload():
    try:
        ytLink = link.get().strip()
        if not ytLink:
            print("请输入YouTube链接")
            return
        
        yt = YouTube(ytLink)
        stream = yt.streams.get_highest_resolution()
        stream.download()
        print(f"下载完成:{yt.title}")
    except RegexMatchError:
        print("YouTube链接格式无效")
    except Exception as e:
        print(f"下载失败:{str(e)}")

# 初始化应用
app = customtkinter.CTk()
app.title("YouTube视频下载器")
app.geometry("500x200")

# 链接输入框
url_var = tkinter.StringVar()
link = customtkinter.CTkEntry(app, width=400, height=40, textvariable=url_var)
link.pack(pady=20)

# 下载按钮
download = customtkinter.CTkButton(app, text="下载", command=startDownload)
download.pack(padx=10, pady=10)

app.mainloop()

额外注意事项

  • 确保pytube为最新版本(YouTube页面结构频繁更新,旧版本易失效):
    pip install --upgrade pytube
    
  • 若仍失败,可能是视频版权限制、地区封锁或网络问题,可通过捕获的具体异常信息进一步排查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 02:01:26