Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Download m3u8 File for Python
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~")
# Use FFmpeg
import os
import time
import requests
import subprocess
# 下载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)
command = 'ffmpeg -i "{}" "{}"'.format(video_download_url, multimedia_path)
popen = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
lines = 0
while True:
next_line = popen.stdout.readline()
line = next_line.rstrip().decode('utf8')
if line == '' and popen.poll() != None:
break
lines += 1
print(length, '-', lines)
if lines%7 == 0:
time.sleep(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment