代碼可以直接運(yùn)行。
# -*- coding: utf-8 -*-
from urllibimport request
import os
from multiprocessingimport Pool
from globimport glob
def run(i):
url ="https://hong.tianzhen-zuida.com/20191220/16480_107655d7/1000k/hls/3564346f72c00000"+str(i)+".ts"
? ? print("開始下載:"+url)
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36"}
r = request.Request(url, headers = headers)
# print(r.content)
? ? try:
downloaded_file =open('./mp4/{}'.format(url[-10:]),'wb')
req = request.Request(url, headers={'User-Agent':'Mozilla/5.0'})
file_on_web = request.urlopen(req)
print("downloading...")
while True:
buf = file_on_web.read(65536)
if len(buf) ==0:
break
? ? ? ? ? ? downloaded_file.write(buf)
downloaded_file.close()
file_on_web.close()
print("done")
except request.ContentTooShortError:
print('Network conditions is not good.Reloading.')
else:
return ""
# 對(duì)轉(zhuǎn)換的TS文件進(jìn)行排序
def get_sorted_ts(user_path):
ts_list = glob(os.path.join(user_path, '*.ts'))
boxer = []
for tsin ts_list:
if os.path.exists(ts):
# print(os.path.splitext(os.path.basename(ts)))
? ? ? ? ? ? file, _ = os.path.splitext(os.path.basename(ts))
print(int(file.replace("c", "")))
boxer.append(int(int(file.replace("c", ""))))
boxer.sort()
print(boxer)
return boxer
# 文件合并
def convert_m3u8(boxer, o_file_name):
# cmd_arg = str(ts0)+"+"+str(ts1)+" "+o_file_name
? ? tmp = []
for tsin boxer:
print(ts)
tmp.append("mp4\\c00000" +str(ts) +'.ts')
cmd_str ='+'.join(tmp)
exec_str ="copy /b " + cmd_str +' ' +" mp4\\" + o_file_name
print(exec_str)
res = os.popen(exec_str)
print(res.read())
if __name__ =='__main__':
# 創(chuàng)建進(jìn)程池,執(zhí)行10個(gè)任務(wù)
? ? print("開始執(zhí)行")
pool = Pool(10)
for iin range(10):
pool.apply_async(run, (i,))#執(zhí)行任務(wù)
? ? pool.close()
pool.join()
print('下載完成!')
user_path ="E:\\code\\Python\\mp4\\"
? ? o_file_name ="慶余年第一季(2019)第46集.mp4"
? ? boxer = get_sorted_ts(user_path)
convert_m3u8(boxer,o_file_name)
os.system('del /Q mp4\\*.ts')
print("刪除文件")
print('ok!處理完成')