Pytube出现AttributeError: 'NoneType'对象无'span'属性问题求助
解决pytube
get_throttling_plan 报错问题 问题背景
昨日正常运行的音频下载代码,今日在本地、Colab及VPS环境均触发报错,错误指向pytube/cipher.py的get_throttling_plan函数第411行,尝试手动修改cipher.py未解决问题。
报错信息:
/usr/local/lib/python3.9/dist-packages/pytube/cipher.py in get_throttling_plan(js) 409 match = plan_regex.search(raw_code) 410 --> 411 transform_plan_raw = find_object_from_startpoint(raw_code, match.span()[1] - 1) 412 413 # Steps are either c[x](c[y]) or c[x](c[y],c[z])
使用代码:
from pytube import YouTube def audio_download(video_url): audio_file = YouTube(video_url).streams.filter(only_audio=True).first().download(filename="audio.mp4") return 'ok'
解决方案
1. 升级pytube至开发版
YouTube频繁更新加密逻辑,官方稳定版可能未同步修复,直接安装最新开发分支:
pip install git+https://github.com/pytube/pytube.git --upgrade
2. 手动修复get_throttling_plan函数
若升级无效,替换cipher.py中get_throttling_plan函数代码:
def get_throttling_plan(js: str) -> list: plan_regex = re.compile(r'a\.[a-zA-Z]\s*&&\s*\([a-z]\s*=\s*a\.get\("n"\)\)\s*&&\s*' r'\([a-z]\s*=\s*([a-zA-Z0-9$]+)(\[\d+\])?\([a-z]\)', re.DOTALL) match = plan_regex.search(js) if not match: raise RegexMatchError( caller="get_throttling_plan", pattern=plan_regex.pattern ) transform_start = match.span()[1] transform_plan_raw = find_object_from_startpoint(js, transform_start - 1) return parse_transform_plan(transform_plan_raw)
3. 切换至yt-dlp替代
yt-dlp对YouTube的更新适配更及时,可直接替换为以下代码:
import yt_dlp def audio_download(video_url): ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'audio.mp4', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp4', }], } with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) return 'ok'
原因说明
该报错因YouTube更新了视频请求节流的JS逻辑,pytube原有正则表达式无法匹配新的代码结构,导致match对象为None,调用match.span()时触发错误。
内容的提问来源于stack exchange,提问作者Mohamed Hasan
相关产品推荐
相关产品推荐

