使用pytube 15.0.0获取YouTube视频标题报错,求解决方法
问题:pytube调用title属性触发KeyError: 'videoDetails'
已将pytube更新至15.0.0版本并使用补丁,但调用YouTube对象的title属性时触发KeyError: 'videoDetails',进而抛出PytubeError。
代码:
from pytube import YouTube print("input url below:") input_url = input() my_video = YouTube(input_url) if input_url == "": pass else: print(my_video.title) print(my_video.thumbnail_url) my_video = my_video.streams.get_lowest_resolution print(my_video)
报错信息:
Traceback (most recent call last): File "C:\Users\(censored)\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pytube\__main__.py", line 330, in title self._title = self.vid_info['videoDetails']['title'] ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^ KeyError: 'videoDetails' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\Users\(censored)\Desktop\youtube video downloader\main.py", line 9, in <module> print(my_video.title) ^^^^^^^^^^^^^^ File "C:\Users\(censored)\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\pytube\__main__.py", line 335, in title raise exceptions.PytubeError( pytube.exceptions.PytubeError: Exception while accessing title of https://youtube.com/watch?v=vEQ8CXFWLZU. Please file a bug report at https://github.com/pytube/pytube
修复思路
- 修正代码语法错误:最后一行
my_video = my_video.streams.get_lowest_resolution缺少调用括号,应改为my_video = my_video.streams.get_lowest_resolution(),否则只会输出方法对象而非流实例。 - 替换pytube源码解析逻辑:该错误源于YouTube页面结构更新,pytube原有
vid_info解析逻辑失效。找到pytube/__main__.py中的title属性定义,替换为以下内容,改用player_response字段提取标题:@property def title(self): if self._title: return self._title self._title = self.player_response['videoDetails']['title'] return self._title - 增加异常捕获与备用方案:在代码中捕获
KeyError和PytubeError,当pytube内置方法失效时,通过网页HTML解析获取标题:
修改代码中的输出部分:else: try: print(my_video.title) except (KeyError, PytubeError): import requests from bs4 import BeautifulSoup resp = requests.get(input_url) soup = BeautifulSoup(resp.text, 'html.parser') og_title = soup.find("meta", property="og:title") if og_title: print(og_title["content"]) print(my_video.thumbnail_url) - 验证URL有效性:确保输入的是完整且有效的YouTube视频链接,避免输入空值、短链接或非视频页面地址。
内容的提问来源于stack exchange,提问作者Faust
相关产品推荐
相关产品推荐

