使用Pytube下载YouTube视频遇^\w+\W匹配失败错误求助
Pytube下载YouTube视频时出现
__init__: could not find match for ^\w+\W错误的解决方法 问题背景
使用以下代码通过Pytube下载YouTube视频,昨日运行正常,今日在Google Colab(德国地区)执行时,指定分辨率触发正则匹配错误:
from pytube import YouTube def download_video(url, resolution): try: yt = YouTube(url) streams = yt.streams.filter(res=f'{resolution}p', progressive=True).first() if streams: print(f"Downloading {yt.title} in {resolution}p resolution...") streams.download() print("Download completed successfully!") else: print(f"No {resolution}p resolution available for this video.") except Exception as e: print("An error occurred:", str(e)) if __name__ == "__main__": url = input("Enter the YouTube video link: ") resolution = input("Enter the desired resolution (e.g., 144, 240, 360, 480, 720, 1080): ") download_video(url, resolution)
错误信息:
An error occurred: __init__: could not find match for ^\w+\W
尝试修改cipher.py第30行正则为var_regex = re.compile(r"^$\w+\W"),但问题未解决。
解决方法
这个错误源于YouTube更新了视频加密的JS逻辑,导致Pytube的正则表达式无法匹配新的变量格式,结合你的场景,按以下步骤处理:
1. 优先升级Pytube到最新版本
Colab默认安装的Pytube版本可能滞后,直接升级到修复了该问题的最新版本:
!pip install --upgrade pytube
2. 若升级后仍报错,手动修正正则表达式
如果升级后问题依旧,找到Colab中Pytube的cipher.py文件(路径通常为/usr/local/lib/python3.x/dist-packages/pytube/cipher.py),将第30行的:
var_regex = re.compile(r"^\w+\W")
替换为:
var_regex = re.compile(r"^\$*\w+\W")
(注:你之前的修改错误地将$放在了^之后,正确的写法是^\$*,表示匹配以0个或1个$开头的变量名)
3. 额外提示:地区限制适配
由于你在德国地区,部分视频可能有地域限制,若下载时出现额外权限错误,可确认视频本身可在德国地区访问,必要时可添加代理参数初始化YouTube对象。
内容的提问来源于stack exchange,提问作者Abbas Mohamadi
相关产品推荐
相关产品推荐

