Python的m3u8下载器源码

import requests
import re
import os 
from tqdm import tqdm
import _thread
import time
from tqdm import tqdm

class m3u8_down():   
    nameSeed = "my" //分段文件名
    
    target_name = "target" //目标文件名
    
    file_count = 0 //分段数目
    
    name_arr = [] //分段文件名
    
    delay_time = 0.1 //下载延迟
    
    headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
            }
    def m3u8_par(self,o):
        m3u8_url = o
        
        m3u8_content = open(o,'r').read()
        

        m3u8_content = re.sub('#EXTM3U','',m3u8_content)
        m3u8_content = re.sub('##EXT-X-VERSION:\d','',m3u8_content)
        m3u8_content = re.sub('#EXT-X-TARGETDURATION:\d','',m3u8_content)
        m3u8_content = re.sub('#EXT-X-MEDIA-SEQUENCE:\d','',m3u8_content)
        m3u8_content = re.sub('#EXTINF:\d\.\d+,','',m3u8_content)
        m3u8_content = re.sub('#EXT-X-VERSION:\d','',m3u8_content)
        m3u8_content = re.sub('#EXT-X-ENDLIST','',m3u8_content)
        m3u8_content = re.sub('#EXTINF:\d+\.\d+,','',m3u8_content)
        m3u8_content = re.sub('#EXTINF:\d+\.\d+,','',m3u8_content)
        
        m3u8_content = re.sub('#EXT-X-KEY:METHOD=AES-128.*','',m3u8_content).split()
        
        return m3u8_content
                   
    def down1(self,m3u8,name):
        
        r = requests.get(url = m3u8,headers = self.headers)
        
        with open(name,"wb")as f:
        
            f.write(r.content)
    

    def fastDown(self,m3u8_content,nameList):
        count = 0
        for i in tqdm(m3u8_content):
            
            _thread.start_new_thread( self.down1, (i, nameList[count] ) )
            time.sleep(self.delay_time)
            count = count +1
            
    def getsegementName(self,nameSeed,count):
        arr = []
        for i in range(count):
            arr.append(nameSeed+str(i).zfill(3)+".ts")
        self.name_arr = arr
        return arr   
            

    def toV1(self):
     

        #shell_str = f'ffmpeg -loglevel quiet -y -i concat:"{title}{str(count-1)}.ts|{filename}" -acodec copy -vcodec copy {title}{str(count)}.ts'
        shell_str = f'copy /b *.ts {target_name}.mp4'
        os.system(shell_str)
        
        
    def remove(self):
        try:
            for i in self.name_arr:
                #print(self.name_arr)
                os.remove(i)
        except FileNotFoundError:
            pass
            
    def start(self,path):
        lis =  self.m3u8_par(path)   //分段地址列表   
        count = len(lis) //分段数字
        arr  = self.getsegementName(self.nameSeed,count ) //分段文件名
        self.fastDown(lis,arr)
        self.toV1()
        self.remove()
    


调用如下
start(m3u8_file) 可修改target_name 修改文件名

你可能感兴趣的:(python)