【m3u8】python使用m3u8库下载视频

1、m3u8库

https://pypi.org/project/m3u8/

 

2、安装

pip install m3u8

 

 

3、使用

复制代码
import time
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
import requests
import m3u8

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}


def get_real_url(url):
    playlist = m3u8.load(uri=url, headers=headers)
    return playlist.playlists[0].absolute_uri


def AESDecrypt(cipher_text, key, iv):
    cipher_text = pad(data_to_pad=cipher_text, block_size=AES.block_size)
    aes = AES.new(key=key, mode=AES.MODE_CBC, iv=key)
    cipher_text = aes.decrypt(cipher_text)
    return cipher_text


def download_m3u8_video(url, save_name):
    real_url = get_real_url(url)
    playlist = m3u8.load(uri=real_url, headers=headers)
    key = requests.get(playlist.keys[-1].uri, headers=headers).content

    n = len(playlist.segments)
    size = 0
    start = time.time()
    for i, seg in enumerate(playlist.segments, 1):
        r = requests.get(seg.absolute_uri, headers=headers)
        data = r.content
        data = AESDecrypt(data, key=key, iv=key)
        size += len(data)
        with open(save_name, "ab" if i != 1 else "wb") as f:
            f.write(data)
        print(
            f"\r下载进度({i}/{n}),已下载:{size/1024/1024:.2f}MB,下载已耗时:{time.time()-start:.2f}s", end=" ")


download_m3u8_video('https://xxx/playlist.m3u8', 'xxxxxx.mp4')
复制代码

备注:

如果视频无加密,可以去除加密部分的代码,直接遍历请求每个ts链接,然后写入文件,再合并即可

 

 

 

 

参考链接:

https://xxmdmst.blog.csdn.net/article/details/118347004

https://www.jianshu.com/p/39d5b2f054f7

https://blog.csdn.net/sinat_31062885/article/details/124608519

https://cloud.tencent.com/developer/article/2089027

 

posted @   代码诠释的世界  阅读(2361)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-04-22 【Mac】开启用户ssh远程登录
2022-04-22 【ubuntu20.04】安装Sonatype Nexus Repository Manager OSS仓库管理私服
点击右上角即可分享
微信分享提示