很多视频网站,可以在线免费看,但是无法下载。一般情况下,网站视频播放是采用了m3u8技术。M3U8是一种基于HTTP Live Streaming (HLS) 协议的播放列表格式,广泛应用于在线视频播放,特别是在直播和点播场景中。让AI写一个下载程序,就可以下载大部分在线视频网站的视频到本地电脑中了。
在ChatGPT中输入提示词:
写一个Python程序,可以下载网页中的m3u8视频,具体步骤:用户输入一个视频地址,然后检测网页中的mu3u8视频地址,然后开始下载mu3u8视频,保存到文件夹:D:\Camera Roll\85100071_480p_20240520094120
ChatGPT的回复:
以下是一个基于 yt-dlp 的 Python 脚本,可以自动检测网页中的 M3U8 视频地址并下载保存到指定目录:
步骤:
用户输入视频网页地址。
使用 yt-dlp 自动解析 M3U8 地址。
下载视频并保存到指定文件夹。
代码示例:
python
复制
编辑
import os
import subprocess
def download_m3u8_video(video_url, output_path):
os.makedirs(output_path, exist_ok=True)
output_file = os.path.join(output_path, "downloaded_video.mp4")
command = [
"yt-dlp",
"-f", "best", # 自动选择最佳格式
video_url,
"-o", output_file
]
try:
print(f"开始下载:{video_url}")
subprocess.run(command, check=True)
print(f"视频下载完成,保存到:{output_file}")
except subprocess.CalledProcessError as e:
print("下载失败:", e)
if __name__ == "__main__":
video_url = input("请输入视频网页地址:")
output_path = r"D:\Camera Roll\85100071_480p_20240520094120"
download_m3u8_video(video_url, output_path)
运行环境配置:
安装 yt-dlp
在终端中运行以下命令安装 yt-dlp:
bash
复制
编辑
pip install yt-dlp
运行脚本
输入视频网页地址,脚本将自动下载视频并保存为 downloaded_video.mp4。
运行该程序,显示:
请输入视频网页地址:https://view\_video.php?viewkey=679f8ddb1c1d6
开始下载:https://view\_video.php?viewkey=679f8ddb1c1d6
WARNING: "-f best" selects the best pre-merged format which is often not the best option.
To let yt-dlp download and merge the best available formats, simply do not pass any format selection.
If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning
Extracting URL: https://view\_video.php?viewkey=679f8ddb1c1d6
679f8ddb1c1d6: Downloading pc webpage
679f8ddb1c1d6: Downloading m3u8 information
679f8ddb1c1d6: Downloading m3u8 information
679f8ddb1c1d6: Downloading m3u8 information
679f8ddb1c1d6: Downloading m3u8 information
679f8ddb1c1d6: Downloading JSON metadata
[info] 679f8ddb1c1d6: Downloading 1 format(s): hls-3075
[hlsnative] Downloading m3u8 manifest
[hlsnative] Total fragments: 109
[download] Destination: D:\Camera Roll\85100071_480p_20240520094120\downloaded_video.mp4
[download] 100% of 166.29MiB in 00:01:03 at 2.63MiB/s
[FixupM3u8] Fixing MPEG-TS in MP4 container of "D:\Camera Roll\85100071_480p_20240520094120\downloaded_video.mp4"
视频下载完成,保存到:D:\Camera Roll\85100071_480p_20240520094120\downloaded_video.mp4
看来已经可以下载视频了,不过要修改一下才更加完善。
继续输入提示词:
修改一下:1、一个视频下载完成后,继续接受用户输入视频地址,不要退出 ;2、下载之前先检测视频文件名是否和文件夹中的已有视频文件名是否重名,如果重名,就更改一下视频的文件名
下面是改进后的 Python 程序,实现以下功能:
持续接受用户输入视频地址:一个视频下载完成后,继续接受用户输入,不退出程序。
避免文件名重名冲突:下载前检查文件名是否重名,如重名则自动生成新的文件名。
python代码示例:
import os
import subprocess
import re
def sanitize_filename(filename):
"""清理文件名,移除非法字符"""
return re.sub(r'[<>:"/\|?*]', '_', filename)
def get_unique_filename(output_path, base_filename):
"""生成唯一的文件名"""
filename = sanitize_filename(base_filename) + ".mp4"
full_path = os.path.join(output_path, filename)
counter = 1
while os.path.exists(full_path):
filename = f"{sanitize_filename(base_filename)}_{counter}.mp4"
full_path = os.path.join(output_path, filename)
counter += 1
return full_path
def download_m3u8_video(video_url, output_path):
try:
print("正在检测视频标题...")
result = subprocess.run(
["yt-dlp", "--get-title", video_url],
capture_output=True,
text=True,
check=True
)
base_filename = result.stdout.strip()
print(f"检测到视频标题:{base_filename}")
except subprocess.CalledProcessError:
print("无法检测视频标题,使用默认文件名")
base_filename = "video"
output_file = get_unique_filename(output_path, base_filename)
command = [
"yt-dlp",
"-f", "best", # 自动选择最佳格式
video_url,
"-o", output_file
]
try:
print(f"开始下载:{video_url}")
subprocess.run(command, check=True)
print(f"视频下载完成,保存到:{output_file}")
except subprocess.CalledProcessError as e:
print("下载失败:", e)
if __name__ == "__main__":
output_path = r"D:\Camera Roll\85100071_480p_20240520094120"
os.makedirs(output_path, exist_ok=True)
while True:
video_url = input("\n请输入视频网页地址(输入 'exit' 退出):").strip()
if video_url.lower() == "exit":
print("程序已退出。")
break
if video_url:
download_m3u8_video(video_url, output_path)
else:
print("无效地址,请重新输入。")
运行说明:
每次输入视频地址后会自动下载,不退出程序。
如果检测到文件名重名,会自动添加序号避免冲突。
输入 exit 退出程序。