iHTCboy
2020-03-09 14:50:55 +08:00
Python 来一波!
```python3
import os
import requests
# 下载 m3u8 格式的视频
def download_m3u8(video_download_url, multimedia_path):
print("start download video")
all_content = requests.get(video_download_url).text # 获取 M3U8 的文件内容
file_line = all_content.split("\n") # 读取文件里的每一行
length = len(file_line)
print('video length:', length)
# 通过判断文件头来确定是否是 M3U8 文件
if file_line[0] != "#EXTM3U":
raise BaseException(u"非 M3U8 的链接")
else:
unknow = True # 用来判断是否找到了下载的地址
for index, line in enumerate(file_line):
if "EXTINF" in line:
unknow = False
# 拼出 ts 片段的 URL
pd_url = video_download_url.rsplit("/", 1)[0] + "/" + file_line[index + 1]
res = requests.get(pd_url)
print(length, '-', index)
with open(multimedia_path, 'ab') as f:
f.write(res.content)
f.flush()
if unknow:
raise BaseException("未找到对应的下载链接")
else:
print("video download finish~")
```