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
#coding:utf-8
import requests
import os
from concurrent.futures import ThreadPoolExecutor

def download_video_segment(i, base_url, output_directory):
"""
下载单个视频片段
"""
#num_str = str(i).zfill(6)
output_filename = os.path.join(output_directory, f"video_{i}.ts")

# 检查文件是否已存在,如果存在则跳过下载
if os.path.exists(output_filename):
print(f"Video {i + 1} already downloaded, skipping...")
return

#url = f"{base_url}{num_str}.ts"
url = f"{base_url}{i}.ts"
response = requests.get(url, stream=True)

if response.status_code == 200:
with open(output_filename, 'wb') as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print(f"Downloaded video {i + 1}")
else:
print(f"Failed to download video from {url}")

# 用户输入的URL、视频名称和结束索引
#user_input_url = input("请输入视频片段的URL:")
base_url = input("请输入视频片段的URL:")
video_name = input("请输入视频的名称:")
end_index = int(input("请输入视频的结束索引:"))

# 处理URL以生成base_url
#base_url = user_input_url.rstrip("-1.ts")

# 下载视频的其他参数
start_index = 1
output_directory = "downloaded_videos"

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

# 使用线程池进行多线程下载
with ThreadPoolExecutor(max_workers=10) as executor:
for i in range(start_index, end_index + 1):
executor.submit(download_video_segment, i, base_url, output_directory)

# 检查下载并合并视频片段
video_files = [os.path.join(output_directory, f"video_{i}.ts") for i in range(start_index, end_index + 1)]
missing_files = [f for f in video_files if not os.path.exists(f)]

if missing_files:
print("以下视频片段缺失,无法进行合并:", missing_files)
else:
# 所有文件都存在,可以合并视频
video_files_str = "|".join(video_files)
output_file_name = f"{video_name}.mp4"
command = f"ffmpeg -i \"concat:{video_files_str}\" -c copy {output_file_name}"
os.system(command)
print(f"Videos have been merged into {output_file_name}!")


使用方式:python3 fs2mp4_v5.py
输入参数url地址

例如,网站的地址是
https://videos/xxxxxxxxxxx/g=210005-10.ts
那么输入的url参数就是https://videos/xxxxxxxxxxx/g=210005-

输入参数url的结束索引,例如500
那么意味着将会从 https://videos/xxxxxxxxxxx/g=210005-1.tshttps://videos/xxxxxxxxxxx/g=210005-500.ts

会下载500个ts文件,并把它合并为一个MP4视频。