python 窗口化 & 多线程(返回值)& 下载M3U8
import math
import os
import re
import shutil
import tkinter.messagebox
from concurrent.futures import ThreadPoolExecutor
from tkinter import *
from tkinter import ttk
import requests
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'
}
dow_list = []
def dowload_data(data_url):
data = requests.get(data_url)
name = data_url[-9:]
with open('.\\bak\\' + name, 'wb') as code:
code.write(data.content)
per = math.floor(abs(int(name[:-3])) * 100 / int(len(dow_list)))
return(int(per))
def merge_movie(name, movie_name):
name = name[-9:]
with open('.\\bak\\' + name, 'rb') as code:
data = code.read()
with open(movie_name+'.ts', 'ab') as code:
code.write(data)
data = None
def dow_m3u8(target, movie_name, pool_num):
os.makedirs('bak') if os.path.exists('bak') == False else None
index_req = requests.get(url=target, headers=headers)
index_url = target[:-10] + index_req.text.split()[2]
file_req = requests.get(url=index_url, headers=headers)
file_name_list = re.findall(',([\W\w]*?).ts', file_req.text)
for i in file_name_list:
file_name = str(i).replace('\n', '') + '.ts'
dowload_url = index_url[:-10] + file_name
dow_list.append(dowload_url)
pool = ThreadPoolExecutor(max_workers=int(pool_num))
for per in pool.map(dowload_data, dow_list):
bar(per)
for i in dow_list:
merge_movie(i, movie_name)
shutil.rmtree('bak')
def button_click():
b1.config(state=DISABLED,text = '正在下载中!')
window.update()
target = d_url.get()
movie_name = m_name.get()
pool_num = p_num.get()
dow_m3u8(target, movie_name, pool_num)
messagebox.showinfo('提示', '下载完成!')
b1.config(state=tkinter.ACTIVE,text='开始下载')
def bar(per):
pb["value"] = +int(per)
window.update()
if __name__ == '__main__':
window = Tk()
window.title('M3U8下载 By: Lswzw...')
window.geometry('560x140')
Label(window, text='下载地址:', font=('Arial', 10), ).place(x=10, y=20)
d_url = StringVar()
url_tk = Entry(window, textvariable=d_url, show=None, width=66,)
url_tk.place(x=88, y=20)
Label(window, text='文件名称:', font=('Arial', 10), ).place(x=10, y=50)
m_name = StringVar()
name_tk = Entry(window, textvariable=m_name, show=None, width=41)
name_tk.place(x=88, y=50)
name_tk.insert(0, '电影名')
Label(window, text='进程数:', font=('Arial', 10), ).place(x=390, y=50)
p_num = StringVar()
pool_tk = Entry(window, textvariable=p_num, show=None, width=14)
pool_tk.place(x=452, y=50)
pool_tk.insert(0, '44')
b1 = Button(window, text='开始下载', width=15, height=1,command=button_click)
b1.place(x=425, y=92)
pb = ttk.Progressbar(window, length=380, mode="determinate", orient=HORIZONTAL)
pb.grid(row=1, column=1)
pb.place(x=25, y=95)
pb["maximum"] = 100
pb["value"] = 0
window.mainloop()