目录结构:
| -- m3u8_get_sdnlab
| -- get_sdnlab_video.py
| -- Netdevops_gongju.m3u8
代码:
# !/usr/bin/python3
# -*- coding=utf-8 -*-
# @File : get_sdnlab_video.py
import os
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
#关闭安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
def getTsUrl():
ts_url_list = []
baseUrl = "https://open.v.sdnlab.com/430d22098c6e4399bf03424b8407b24e/act-m3u8-segment/"
with open("Netdevops_gongju.m3u8", 'r', encoding="utf-8") as f:
m3u8Contents = f.readlines()
for content in m3u8Contents:
if content.endswith('ts\n'):
ts_Url = baseUrl + content.replace('\n', '').replace('..', '')
ts_url_list.append(ts_Url)
print(ts_Url)
return ts_url_list
def download_ts_video(ts_url_list):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36",
}
download_path = os.path.join(os.path.abspath(os.curdir), 'download_ts_video')
if not os.path.exists(download_path):
print('Directory is not exists, Start building ==>')
os.makedirs(download_path)
for i in range(len(ts_url_list)):
ts_url = ts_url_list[i]
try:
response = requests.get(ts_url, headers=headers, stream=True, verify=False)
except Exception as e:
print('Exception requests: %s' % e.args)
return
ts_path = os.path.join(download_path, (str(i) + '.ts'))
with open(ts_path, "wb") as file:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
print('开始下载:%s' % ts_url_list[i])
print("TS文件下载完毕")
def getDirFilePath():
down_TsVideo_dir = os.path.join(os.path.abspath(os.curdir), 'download_ts_video')
if os.path.exists(down_TsVideo_dir):
file_list = [os.path.join(root, filespath) for root, dirs, files in os.walk(down_TsVideo_dir) for filespath in files if str(filespath).endswith('ts')]
return file_list
def mergeTsVideo(download_path, merge_files_path):
all_ts = (os.listdir(download_path))
all_ts.sort(key=lambda x: int(x[:-3]))
with open(merge_files_path, 'wb+') as f:
for i in range(len(all_ts)):
# print(len(all_ts))
print(i)
ts_video_path = os.path.join(download_path, all_ts[i])
f.write(open(ts_video_path, 'rb').read())
print("合并完成!!")
if __name__ == "__main__":
download_path = r"D:\pythontest\100-temp_test\05-test\download_ts_video"
merge_files_path = r"D:\pythontest\100-temp_test\05-test\国外NetDevOps资源及工具清单分享.mp4"
mergeTsVideo(download_path, merge_files_path)
# ts_url = getTsUrl()
# download_ts_video(ts_url)