Pytube 15.0.0出现RegexMatchError,如何修复视频下载功能?
解决Pytube 15.0.0的RegexMatchError下载错误
问题详情
用Pytube 15.0.0写的视频下载代码前一天还正常运行,今天突然报错:
RegexMatchError: get_throttling_function_name: could not find match for multiple
原有代码:
def video_indir(video_url, dosya_adi): video = pytube.YouTube(video_url) audio_stream = video.streams.filter(only_audio=True).first() audio_dosya = f'{dosya_adi}.mp4' audio_stream.download(filename=audio_dosya) return audio_dosya
修复方法
方法一:修改pytube源码
问题根源是YouTube更新了页面JS结构,原正则表达式末尾多了个分号,导致匹配失败:
- 找到Python环境中pytube包的安装路径,打开
cipher.py文件 - 定位到第287行,把原代码:
改成:r'var {nfunc}\s*=\s*(\[.+?\];)'.format(
(核心是去掉正则里的r'var {nfunc}\s*=\s*(\[.+?\])'.format(;,现在YouTube的变量定义末尾不再带分号)
方法二:无需修改源码,重写匹配方法
不想改动第三方库源码的话,直接在自己的代码里重写对应的方法即可:
from pytube import YouTube from pytube.cipher import Cipher, RegexMatchError # 重写修复后的匹配方法 def fixed_get_throttling_function_name(js: str) -> str: pattern = r'var\s+([a-zA-Z0-9_$]+)\s*=\s*(\[.+?\])' match = Cipher.regex_search(pattern, js) if not match: raise RegexMatchError( caller="get_throttling_function_name", pattern=pattern ) return match.group(1) # 替换pytube原方法 Cipher.get_throttling_function_name = fixed_get_throttling_function_name def video_indir(video_url, dosya_adi): video = YouTube(video_url) audio_stream = video.streams.filter(only_audio=True).first() audio_dosya = f'{dosya_adi}.mp4' audio_stream.download(filename=audio_dosya) return audio_dosya
内容的提问来源于stack exchange,提问作者SÜLEYMAN YAŞAR
相关产品推荐
相关产品推荐

