当前位置:首页 > Python > 正文内容

使用Python将m3u8文件保存到本地

2年前 (2022-07-06)Python

昨天在家看在线电影,结果家里网络比较卡,所以没有能愉快的看完,上班的时候想要把昨天没看完的电影下载下来,结果因为版权问题,没地方可下载,于是打开F11,在播放的时候会调用m3u8的文件,文件里有很多ts文件,我下载了其中一个,然后发现这是影片其中几秒,如果把m3u8里的所有ts文件下载回来再合并,就是一个完整的影片里。说干就干,使用Python。

代码如下

import requests
import os
import time
file = "index.m3u8"
lines = []
with open(file,'r') as f:
	lines = f.readlines()
tsList = []
for line in lines:
	if line[0:6] == "https:":
		tsList.append(line)
i = 0
print("开始下载ts列表")
tsPath = "/ts/"

headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"}

for url in tsList:
	url = url.replace("\n", "")
	tsName = url.split('/')[-1]
	requests.adapters.DEFAULT_RETRIES = 99999
	s = requests.session()
	s.keep_alive = False
	
	if(os.path.exists(tsPath + tsName) == False):
		time.sleep(1)
		print("正在下载=>"+url)
		try:
			urlData = requests.get(url, cert=('/Users/ths/Tools/m3u8down/client.crt', '/Users/ths/Tools/m3u8down/client.key'), headers=headers).content
			with open(tsPath + tsName, "wb") as tsP:
				tsP.write(urlData)
		except OSError as reason:
			print('下载失败=>%s'%str(url))
	else:
		print("存在文件跳过=>"+tsPath + tsName)
	i = i+1
print("下载完成")

下载完成后 合并的python如下

import requests
import os

file = "index.m3u8"
lines = []
with open(file,'r') as f:
	lines = f.readlines()
tsList = []
mergeFile = open("merge.ts","wb+")
tsPath = "/ts/"
for line in lines:
	if line[0:6] == "https:":
		tsList.append(line)
for url in tsList:
	url = url.replace("\n", "")
	tsName = url.split('/')[-1]
	with open(tsPath+tsName,"rb") as tsP:
		mergeFile.write(tsP.read())


扫描二维码推送至手机访问。

版权声明:本文由小祥子的博客发布,如需转载请注明出处。

本文地址:http://www.xiaoxiangzi.com/post/1705.html

相关文章

Python获取数据库信息->解压zip->去水印->打包zip

#!/usr/bin/python3 # -*- coding: utf-8 -*- import cv2 import numpy...