使用pytube时为何出现410 Gone错误?
pytube调用时遇到410 Gone错误,升级后仍未解决
问题重现
运行以下获取YouTube视频标题的基础代码时,触发urllib.error.HTTPError: HTTP Error 410: Gone错误:
from pytube import YouTube url = "https://www.youtube.com/watch?v=dQw4w9WgXcQ" # 硬编码的Rick Roll视频 video = YouTube(url) print("*****Video Title*****") print(video.title)
完整报错信息
Traceback (most recent call last): File "/Users/will/Documents/Coding test/import pytube.py", line 4, in <module> video = YouTube(url) File "/Users/will/opt/anaconda3/lib/python3.9/pytube/__main__.py", line 91, in __init__ self.prefetch() File "/Users/will/opt/anaconda3/lib/python3.9/pytube/__main__.py", line 181, in prefetch self.vid_info_raw = request.get(self.vid_info_url) File "/Users/will/opt/anaconda3/lib/python3.9/pytube/request.py", line 36, in get return _execute_request(url).read().decode("utf-8") File "/Users/will/opt/anaconda3/lib/python3.9/pytube/request.py", line 24, in _execute_request return urlopen(request) # nosec File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 214, in urlopen return opener.open(url, data, timeout) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 523, in open response = meth(req, response) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 632, in http_response response = self.parent.error( File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 555, in error result = self._call_chain(*args) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 494, in _call_chain result = func(*args) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 747, in http_error_302 return self.parent.open(new, timeout=req.timeout) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 523, in open response = meth(req, response) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 632, in http_response response = self.parent.error( File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 561, in error return self._call_chain(*args) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 494, in _call_chain result = func(*args) File "/Users/will/opt/anaconda3/lib/python3.9/urllib/request.py", line 641, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 410: Gone
已尝试操作
执行升级命令后问题未解决:
python -m pip install --upgrade pytube
解决方案
- 安装pytube GitHub开发版
PyPI稳定版可能未及时适配YouTube的接口变化,直接安装最新开发代码:
pip install git+https://github.com/pytube/pytube.git
- 手动修改请求头(临时方案)
若安装开发版仍无效,可修改pytube安装目录下的request.py,在_execute_request函数中添加模拟浏览器的请求头:
def _execute_request(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } request = urllib.request.Request(url, headers=headers) return urllib.request.urlopen(request)
- 切换至pytube3分支
如果上述方法都不生效,可尝试使用维护更活跃的分支版本:
pip install pytube3 --upgrade
内容的提问来源于stack exchange,提问作者Willguy24
相关产品推荐
相关产品推荐

