2024最新python使用yt-dlp
2024最新python使用yt-dlp下载YT视频
- 1.获取yt的cookie
- 1)google浏览器下载Get cookies.txt LOCALLY插件
- 2)导出cookie
- 2.yt-dlp下载[yt-dlp的GitHub地址](https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file)
- 1)使用Pycharm(2024.3)进行代码demo编写
- 2)使用的python版本3.9.13
- 3)Pycharm下载对应的第三方库yt-dlp
- 4)使用命令进行下载
- 5)复制cookie到根目录
- 5)python代码
- 6)运行测试
- 3.注意事项
- 1)配置
- 2)yt-dlp配置
- 4.demo项目github地址
1.获取yt的cookie
1)google浏览器下载Get cookies.txt LOCALLY插件
https://chromewebstore.google.com/detail/get-cookiestxt-locally/cclelndahbckbenkjhflpdbgdldlbecc
2)导出cookie
推荐使用cookies方式,因为:
更安全,不需要存储密码
避免频繁登录导致的验证码问题
可以访问账号订阅的内容
支持年龄限制视频的下载
记住要定期更新cookies以确保其有效性。
2.yt-dlp下载yt-dlp的GitHub地址
1)使用Pycharm(2024.3)进行代码demo编写
2)使用的python版本3.9.13
3)Pycharm下载对应的第三方库yt-dlp
4)使用命令进行下载
pip install yt-dlp
提示pip警告
[notice] A new release of pip is available: 23.2.1 -> 24.3.1
[notice] To update, run: python.exe -m pip install --upgrade pip
更新就行了
python.exe -m pip install --upgrade pip
5)复制cookie到根目录
5)python代码
import yt_dlp
from pathlib import Path
import os
def yt_test(url):
try:
# 创建下载目录
video_path = Path("downloads/video")
audio_path = Path("downloads/audio")
video_path.mkdir(parents=True, exist_ok=True)
audio_path.mkdir(parents=True, exist_ok=True)
# yt-dlp 基础配置
common_opts = {
'cookiefile': r'www.youtube.com_cookies.txt',
'quiet': False,
'no_warnings': False,
'verbose': True,
'proxy': 'http://127.0.0.1:10809',
'socket_timeout': 30,
'retries': 3,
'nocheckcertificate': True,
'prefer_insecure': True
}
print("开始下载视频...")
print(f"使用cookies文件: {common_opts['cookiefile']}")
# 视频下载选项
video_opts = {
**common_opts,
'format': 'best[ext=mp4][height<=720]/best[height<=720]/best',
'outtmpl': str(video_path / '%(title)s.%(ext)s'),
}
# 音频下载选项
audio_opts = {
**common_opts,
'format': 'bestaudio[ext=m4a]/bestaudio',
'outtmpl': str(audio_path / '%(title)s.%(ext)s'),
}
# 获取视频信息
print("正在获取视频信息...")
with yt_dlp.YoutubeDL(common_opts) as ydl:
info = ydl.extract_info(url, download=False)
title = info['title']
duration = info['duration']
thumbnail = info['thumbnail']
print(f"视频标题: {title}")
print(f"视频时长: {duration // 60}:{duration % 60:02d}")
print(f"缩略图URL: {thumbnail}")
# 下载视频
print("\n开始下载视频文件...")
with yt_dlp.YoutubeDL(video_opts) as ydl:
ydl.download([url])
# 下载音频
print("\n开始下载音频文件...")
with yt_dlp.YoutubeDL(audio_opts) as ydl:
ydl.download([url])
# 获取下载后的文件路径
video_file = next(video_path.glob(f"{title}.*"))
audio_file = next(audio_path.glob(f"{title}.*"))
print("\n下载完成!")
print(f"视频文件: {video_file}")
print(f"音频文件: {audio_file}")
return {
"status": "success",
"title": title,
"duration": f"{duration // 60}:{duration % 60:02d}",
"thumbnail": thumbnail,
"video_path": str(video_file),
"audio_path": str(audio_file)
}
except Exception as e:
print(f"\n下载过程中出错: {str(e)}")
return {"status": "error", "message": str(e)}
if __name__ == "__main__":
# 测试URL
test_url = "******.com/watch?v=_KFzaJSxBcY"
print("测试")
print("-" * 50)
print(f"测试URL: {test_url}")
print("-" * 50)
result = yt_test(test_url)
if result["status"] == "success":
print("\n测试成功!")
print("-" * 50)
print(f"标题: {result['title']}")
print(f"时长: {result['duration']}")
print(f"视频文件: {result['video_path']}")
print(f"音频文件: {result['audio_path']}")
else:
print("\n测试失败!")
print("-" * 50)
print(f"错误信息: {result['message']}")
6)运行测试
3.注意事项
1)配置
猫: 常用7890
V2: 常用 10808/10809
S: 常用1080
2)yt-dlp配置
common_opts = {
‘cookiefile’: r’cookies.txt’,
‘quiet’: False,
‘no_warnings’: False,
‘verbose’: True,
#和上方的端口进行对应
‘proxy’: ‘http://127.0.0.1:10809’,
‘socket_timeout’: 30,
‘retries’: 3,
‘nocheckcertificate’: True,
‘prefer_insecure’: True
}
4.demo项目github地址
https://github.com/unkownc/python_demo/tree/main