准备 Excel 文件

首先,需要准备一个包含 YouTube 视频名称和链接的 Excel 文件。文件内容的格式如下:

视频名称 视频链接
xxx xxxxxxxxxxxxxxxxxxx
xxxxx xxxxxxxxxxxxxxxxxxx
xxxx xxxxxxxxxxxxxxxxxxx

Excel 文件的要求:

  • 第一列:视频名称(可以是中文或英文,脚本将使用此名称保存下载的视频文件)。
  • 第二列:视频的 YouTube 链接。

文件名为videos.xlsx

安装 Python 和依赖库

需要确保已经安装了 Python 环境。如果没有安装 Python,可以从 Python 官方网站 下载并安装。

安装完成后,打开终端或命令提示符,确保 Python 和 pip 已正确安装。可以通过以下命令检查:

1
2
python --version
pip --version

接下来,安装脚本所需的 Python 库:

  1. openpyxl:用于读取 Excel 文件。
  2. yt-dlp:用于下载 YouTube 视频。https://github.com/yt-dlp/yt-dlp

在终端中运行以下命令来安装所需的库:

1
pip install openpyxl yt-dlp

安装 ffmpeg:

yt-dlp 需要 ffmpeg 来合并分开的视频流和音频流。可以按照以下步骤安装 ffmpeg

  • Windows

    1. 前往 FFmpeg 官方下载页面
    2. 下载 Windows 版本的压缩包(比如 ffmpeg-release)。
    3. 解压文件到一个文件夹,比如 C:\ffmpeg
    4. C:\ffmpeg\bin 文件夹添加到环境变量中(方法:右击 “此电脑” > “属性” > “高级系统设置” > “环境变量” > 在 “系统变量” 中找到 Path,点击编辑,添加 C:\ffmpeg\bin 路径)。
  • Linux (Ubuntu): 执行以下命令安装 ffmpeg

    1
    2
    sudo apt update
    sudo apt install ffmpeg
  • macOS: 使用 Homebrew 安装 ffmpeg

    1
    brew install ffmpeg

验证安装: 安装完成后,你可以通过以下命令验证 ffmpeg 是否安装成功:

1
ffmpeg -version

如果 ffmpeg 安装成功,会显示版本信息。

创建脚本

创建一个新的 Python 文件,复制并粘贴以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from concurrent.futures import ThreadPoolExecutor, as_completed
import os
from openpyxl import load_workbook
import yt_dlp as ytdlp
import re
import time
import logging

# 设置日志记录
logging.basicConfig(filename='download_log.txt', level=logging.INFO, format='%(asctime)s - %(message)s')

# 读取Excel文件
def read_excel(file_path):
workbook = load_workbook(file_path)
sheet = workbook.active
videos = []

for row in sheet.iter_rows(min_row=2, max_col=2, values_only=True):
video_name, video_url = row
if video_name and video_url:
videos.append((video_name, video_url))

return workbook, sheet, videos

# 下载视频并保存
def download_video(video_name, video_url, sheet, download_dir='downloads'):
try:
video_name = clean_filename(video_name)
ydl_opts = {
'outtmpl': os.path.join(download_dir, f'{video_name}.%(ext)s'),
'format': 'bestvideo[height=1080]+bestaudio/best',
'noplaylist': True,
'merge_output_format': 'mp4',
'progress_hooks': [progress_hook], # 可选:添加下载进度钩子函数
}

if not os.path.exists(download_dir):
os.makedirs(download_dir)

with ytdlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([video_url])

logging.info(f"下载成功: {video_name}")
print(f"下载成功: {video_name}")

# 下载成功后,删除对应的 Excel 行
delete_row(sheet, video_name)

except Exception as e:
logging.error(f"下载失败: {video_name}, 错误: {e}")
print(f"下载失败: {video_name}, 错误: {e}")

# 文件名清理函数
def clean_filename(filename):
# 替换非法字符
return re.sub(r'[\\/*?:"<>|]', "_", filename)

# 下载进度钩子函数(可选)
def progress_hook(d):
if d['status'] == 'downloading':
print(f"下载中: {d['filename']} - {d['_percent_str']} 完成")

# 删除 Excel 行
def delete_row(sheet, video_name):
for row in sheet.iter_rows(min_row=2, max_col=2):
if row[0].value == video_name:
sheet.delete_rows(row[0].row, 1)
sheet.parent.save('videos.xlsx') # 保存更改
break

# 主程序并发实现
def main():
excel_file = 'videos.xlsx'
workbook, sheet, videos = read_excel(excel_file)

with ThreadPoolExecutor(max_workers=5) as executor: # 使用5个线程并发下载
future_to_video = {executor.submit(download_video, video_name, video_url, sheet): (video_name, video_url) for video_name, video_url in videos}

for future in as_completed(future_to_video):
video_name, video_url = future_to_video[future]
try:
future.result()
except Exception as e:
logging.error(f"下载失败: {video_name}, 错误: {e}")
print(f"下载失败: {video_name}, 错误: {e}")

time.sleep(2) # 在每次下载后暂停 2 秒

input("所有视频下载完成!按 Enter 键退出...")

if __name__ == "__main__":
main()

将此文件保存为 download_youtube_videos.py

运行脚本

注意事项:运行脚本前备份videos.xlsx,因为运行过程会将下载成功的视频信息从excel表格中删除。

  1. Excel 文件videos.xlsx)和 Python 脚本download_youtube_videos.py)放在同一个文件夹内。

  2. 打开终端(或命令提示符)并导航到文件夹位置:

    1
    cd /path/to/your/folder
  3. 运行脚本:

    1
    python download_youtube_videos.py

    脚本将读取 Excel 文件中的视频链接,并自动开始下载。下载的文件会保存在同一目录下的 downloads 文件夹中,文件名将使用 Excel 中的 视频名称

windowss也可直接双击运行脚本

运行过程