视频下载半自动



import requests,re
from tkinter.filedialog import asksaveasfile
from time import sleep

savef=asksaveasfile('wb')

url_ts2=input('输入一个源地址:')

def f_m3u8(url_m3u8):
    print('m3u8 called')
    try:
        r = requests.get(url_m3u8,timeout=30,headers={'Connection':'close'})
    except:
        num_count=0
        while 1:
            sleep(0.5)
            num_count+=1
            try:
                print('m3u8 retry {}'.format(num_count))
                r = requests.get(url_m3u8,timeout=30,headers={'Connection':'close'})
                if r.status_code == 200 :
                    break
            except:
                continue
            
    list_ts=re.findall('\n.*?\.ts|\n.*?\.jpg',r.text)
    list_ts = list(map(lambda x:x[1:],list_ts))
    print('ts连接数量:',len(list_ts))
    return list_ts
def f_host_parse(url,url2):
    list_url=url.split('/')[:-1]
    list_url2 = url2.split('/')
    pandin = list_url2[0]
    if len(pandin) == 0:
        pandin = list_url2[1]
    list_url3=[]
    for i in list_url:
        if i == pandin:
            break
        else:
            list_url3.append(i)
    url3 = '/'.join(list_url3+list_url2)
    return url3

def f_down(url_ts2):
    print('down called')
    list_ts = f_m3u8(url_ts2)
    
    for i in list_ts:
##        url_ts = url_ts.replace('index.m3u8',str(i))
        url_ts = f_host_parse(url_ts2,i)
        #手动换反斜杆
##        url_ts = url_ts.replace('https://video.twimg.com//','https://video.twimg.com/')
        url_ts = url_ts.replace('//','/')
        url_ts = url_ts.replace(':/','://')
        try:
            print('{}开始下载'.format(url_ts))
            r = requests.get(url_ts,timeout=30,headers={'Connection':'close'})
        except:
            num_count=0
            while 1:
                sleep(0.5)
                num_count+=1
                try:
                    print('m3u8 retry {}'.format(num_count))
                    r = requests.get(url_ts,timeout=30,headers={'Connection':'close'})
                    if r.status_code == 200 :
                        break
                except Exception as e:
                    print(e)
                    continue
        print(len(r.content))
        savef.write(r.content)
        savef.flush()
if __name__ == '__main__':
    f_down(url_ts2)
    
            


你可能感兴趣的:(视频下载半自动)