当前位置: 首页 > news >正文

Python 神器:一键下载 M3U8 并转换为 MP4

在这个数字时代,我们经常在网页上遇到各种精彩的视频,但往往只能观看而无法下载。今天,我将向大家介绍如何使用 Python 自动下载网页中的 M3U8 链接,并将其转换为 MP4 格式,让你轻松保存喜欢的视频!

一、准备工作

首先,确保你已经安装了 ffmpeg。如果还没有安装,可以通过以参考这里安装:https://wizops.net/archives/202404/323.html

二、代码流程

  • 下载 M3U8 文件保存到临时目录。
  • 下载 key 文件保存到临时目录。
  • 生成本地 M3U8 文件内容保存到临时目录。
  • 下载 ts 文件保存到临时目录下的index目录。
  •  使用ffmpeg将m3u8转换成mp4文件

三、代码实现

import os
import urllib3
import requests
import subprocess
from m3u8 import M3U8
from tenacity import retry, wait_random, stop_after_attempt
from gevent.pool import Pool
urllib3.disable_warnings()pool = Pool(10)@retry(stop=stop_after_attempt(3), wait=wait_random(2, 5))
def request(url):"""发送请求"""try:res = requests.get(url, verify=False, timeout=5)return resexcept Exception as e:print(url, e)raise edef download_segment(url, path):"""下载ts文件"""filename = url.split("/")[-1]file = os.path.join(path, filename)if os.path.exists(file):return res = request(url)with open(file, "wb")as f:f.write(res.content)def convert_mp4(path, output):# 使用FFmpeg将local.m3u8转换为一个MP4文件    ffmpeg -allowed_extensions ALL -i index.m3u8 -c copy xxx.mp4# m3u8文件中有key需要带参数-allowed_extensions ALLsubprocess.call(['ffmpeg', '-allowed_extensions', 'ALL', '-i', 'local.m3u8', '-c', 'copy', output], cwd=path)def download_m3u8(url, path, output):"""下载单个m3u8主程序url: m3u8链接urlpath: 单个m3u8目录output: 转换输出文件路径名"""base_url = url.rsplit("/", 1)[0]# 创建目录segment_dir = os.path.join(path, "index")if not os.path.exists(segment_dir):os.makedirs(segment_dir)# 下载M3U8文件m3u8_file_name = os.path.join(path, "index.m3u8")res = request(url)with open(m3u8_file_name, "w", encoding="utf-8")as f:f.write(res.text)# 解析M3U8文件m3u8_obj = M3U8(res.text)print(m3u8_obj.keys)# 下载key文件 for item in m3u8_obj.keys:if item:key_url = item.uri if item.uri.startwith("http") else f"{base_url}/{item.uri}"key_file_name = os.path.join(path, item.uri)res = request(key_url)with open(key_file_name, "w", encoding="utf-8")as f:f.write(res.text)segments = []# 生成新的本地M3U8文件内容for segment in m3u8_obj.segments:segments.append(segment.uri)segment.uri = "index/" + segment.uri.split("/")[-1]# 保存M3U8文件local_file_name = os.path.join(path, "local.m3u8")with open(local_file_name, 'w') as f:f.write(m3u8_obj.dumps())# 下载ts文件for url in segments:pool.spawn(download_segment, url, segment_dir)pool.join()# ts文件下载完成, 转换成mp4文件if len(segments) == len(os.listdir(segment_dir)):convert_mp4(path, output)if __name__ == "__main__":url = "https://v3.mstopq.com/202302/26/E92zcVVNkT1/video/1000k_0X720_64k_25/hls/index.m3u8"cur_path = os.path.abspath(os.path.dirname(__file__))path = os.path.join(cur_path, "终结者创世纪_tmp")output = os.path.join(cur_path, "终结者创世纪.mp4")download_m3u8(url, path, output)

三、注意事项

  • 确保已经安装了 ffmpeg,并且在系统路径中可以访问到。
  • 输出路径必须存在,否则可能会出现错误。
  • 根据实际情况,可能需要根据 M3U8 文件的具体内容调整 ffmpeg 命令的参数。

通过这个简单的示例,你可以使用 Python 自动下载网页中的 M3U8 链接并将其转换为 MP4 格式。现在,你可以轻松保存喜欢的视频,随时随地观看啦!希望这个技巧对你有所帮助。如果有任何问题或建议,欢迎在评论中留言!

http://www.lryc.cn/news/329499.html

相关文章:

  • vue3全局控制Element plus所有组件的文字大小
  • 区间预测 | Matlab实现带有置信区间的BP神经网络时间序列未来趋势预测
  • Matlab中的脚本和函数
  • 使用 nohup java - jar 不输出nohup日志
  • Linux系统中安装一些常用的插件备用
  • 笔记本电脑上部署LLaMA-2中文模型
  • 百度云加速方法「Cheat Engine」
  • SOC内部集成网络MAC外设+ PHY网络芯片方案:PHY芯片基础知识
  • openGauss 6.0.0-RC1 版本正式发布!
  • 【JVM】关于JVM垃圾回收
  • Unity照片墙简易圆形交互效果总结
  • Unity2018发布安卓报错 Exception: Gradle install not valid
  • 蓝桥杯省赛刷题——题目 2656:刷题统计
  • Python爬虫之异步爬虫
  • 【Web】NSSCTF Round#20 Basic 个人wp
  • 【Java笔记】实现延时队列1:JDK DelayQueue
  • npm淘宝镜像源切换
  • ENet——实时语义分割的深度神经网络架构与代码实现
  • 游戏领域AI智能视频剪辑解决方案
  • 腾讯云轻量2核2G3M云服务器优惠价格61元一年,限制200GB月流量
  • leecode 331 |验证二叉树的前序序列化 | gdb 调试找bug
  • 服务器安全事件应急响应排查方法
  • 数码视讯Q7盒子刷armbian或emuelec的一些坑
  • 2_2.Linux中的远程登录服务
  • Spring Boot集成JPA快速入门demo
  • 深度学习理解及学习推荐(持续更新)
  • 【C语言】贪吃蛇【附源码】
  • 【技巧】压缩文件如何设置“自动加密”?
  • 内网穿透时报错【Bad Request This combination of host and port requires TLS.】的原因
  • 计算机网络:物理层 - 信道复用