# -*- coding: utf-8 -*- import requests,threading def getTsUrl(): ts_url_list = [] baseUrl = "https://sy4.3sybf.com" with open("index.m3u8", "r", encoding="utf-8") as f: m3u8Contents = f.readlines() for content in m3u8Contents: if content.endswith("ts\n"): ts_Url = content.replace("\n", "").replace("..", "") ts_url_list.append(baseUrl+ts_Url) #print(ts_Url) return ts_url_list def download_ts_video(download_path, ts_url_list,start,last): # download_path = r"C:\Users\Administrator\Desktop\AiShu\下载视频\TS视频" for i in range(start,last): ts_url = ts_url_list[i] try: response = requests.get(ts_url, stream=True, verify=False) except Exception as e: print("异常请求:%s" % e.args) return #name = ts_url.split('y')[-1].strip() # 截取ts链接的最后一部分,结果为00001.ts name = ts_url[51:] ts_path = download_path + "\{}".format(name) with open(ts_path, "wb+") as file: for chunk in response.iter_content(chunk_size=1024): if chunk: file.write(chunk) def main(total,block,total_vedio): # 启动多线程 start = 0 thread_list = [] # 线程存放列表 for i in range(total): if start + block > total_vedio: t = threading.Thread(target=download_ts_video, args=(download_path,ts_url_list ,start, total_vedio,)) else: t = threading.Thread(target=download_ts_video, args=(download_path,ts_url_list,start , start + block,)) start += block t.setDaemon(True) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() if __name__ == '__main__': download_path = r"D:/pyfile/ts" # 视频保存在本地的地址 total = 20 # 线程总数 ts_url_list = getTsUrl() # 获取所有ts链接 block = int(len(ts_url_list) / total) # 一共有total个线程,那么平均给每一个线程多少个下载任务 if len(ts_url_list) % total != 0: block += 1 #print(getTsUrl()) main(total,block,len(ts_url_list)) #download_ts_video(download_path, ts_url_list,0,len(ts_url_list))