python 下载m3u8视频的示例代码


Posted in Python onNovember 11, 2020
import requests
import os
import datetime
import threading

class xiazai():
  def __init__(self,url):
    self.url = url
    work_dir = os.getcwd()
    # print(work_dir)
    # 用来保存ts文件
    file_dir = os.path.join(work_dir, 'file_tmp')
    if not os.path.exists(file_dir):
      os.mkdir(file_dir)
    self.headers ={
      'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36'
    }
    self.savefile(self.url)

  def savefile(self, file_url):

    r = requests.get(file_url, headers=self.headers)
    # 合成带有hls的m3u8地址
    if r.text.split('\n')[-1] == '':
      hls_mark = r.text.split('\n')[-2] # 以防\n结尾
    else:
      hls_mark = r.text.split('\n')[-1]
    self.url_m3u8_hls = file_url.replace('index.m3u8', hls_mark)
    #file_m3u8 = url_m3u8_hls.split('/')[-1]
    self.duqu()
    #print(url_m3u8_hls)

  def duqu(self):
    r = requests.get(self.url_m3u8_hls, headers=self.headers).text
    text_bytes = r.split('\n')
    # 筛选以.ts结尾的行
    # 有些情况下可能是以其他格式的文件,比如png,下载后修改后缀即可
    # ts_name = [i for i in text_string if i.endswith('.ts')]
    self.ts_time = [i for i in text_bytes if i.startswith('#EXTINF')]
    #self.shijian(dm_time)
    #print(dm_time)
    self.ts_neirong = [i for i in text_bytes if not i.startswith('#')]
    self.ts_neirong.pop()
    self.threads = []
    self.threads.append(threading.Thread(target=self.xiazai))
    self.threads.append(threading.Thread(target=self.shijian))
    for t in self.threads:
      # print(t)
      t.start()
    #self.xiazai(url_m3u8_hls)
    # print(ts_neirong)
  def shijian(self):
    self.dm_time = 0
    for i in range(len(self.ts_time)):
      ts_time1 = self.ts_time[i].replace('#EXTINF:', '')
      ts_time2 = ts_time1.replace(',', '')
      self.dm_time = float(ts_time2) + self.dm_time
    shichang_time = str(datetime.timedelta(seconds=self.dm_time))
    print('视频时长:%s' % shichang_time)
  def xiazai(self):
    liebiao=[]
    for i in range(len(self.ts_neirong)):
      hls_mark = self.url_m3u8_hls.split('/')[-1]
      url_xiazai = self.url_m3u8_hls.replace(hls_mark, self.ts_neirong[i])
      liebiao.append(url_xiazai)
      #print(url_xiazai)
      # r = requests.get(url_xiazai, headers=self.headers)
      # with open('file_tmp/'+ts_neirong[i], 'wb') as f:
      # f.write(r.content)
      # f.close()
    x = self.bisector_list(liebiao, 10)
    self.xiancheng0=x[0]
    self.xiancheng1=x[1]
    self.xiancheng2=x[2]
    self.xiancheng3=x[3]
    self.xiancheng4=x[4]
    self.xiancheng5=x[5]
    self.xiancheng6=x[6]
    self.xiancheng7=x[7]
    self.xiancheng8=x[8]
    self.xiancheng9=x[9]
    self.threads2 = []
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai1))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai2))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai3))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai4))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai5))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai6))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai7))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai8))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai9))
    self.threads2.append(threading.Thread(target=self.xiancheng_xiazai10))

    for t in self.threads2:
      # print(t)
      t.start()


  def xiancheng_xiazai1(self):
    #print(self.xiancheng0)
    for i in self.xiancheng0:
      #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()

  def xiancheng_xiazai2(self):
    #print(self.xiancheng1)
    for i in self.xiancheng1:
      #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi= i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()

  def xiancheng_xiazai3(self):
    #print(self.xiancheng2)
    for i in self.xiancheng2:
      #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()

  def xiancheng_xiazai4(self):
    #print(self.xiancheng3)
    for i in self.xiancheng3:
      #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def xiancheng_xiazai5(self):
    #print(self.xiancheng4)
    for i in self.xiancheng4:
    #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def xiancheng_xiazai6(self):
    #print(self.xiancheng5)
    for i in self.xiancheng5:
    #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def xiancheng_xiazai7(self):
    #print(self.xiancheng6)
    for i in self.xiancheng6:
    #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def xiancheng_xiazai8(self):
    #print(self.xiancheng7)
    for i in self.xiancheng7:
    #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def xiancheng_xiazai9(self):
    #print(self.xiancheng8)
    for i in self.xiancheng8:
    #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def xiancheng_xiazai10(self):
    #print(self.xiancheng9)
    for i in self.xiancheng9:

    #print(i)
      r = requests.get(i, headers=self.headers)
      mingzi = i.split('/')[-1]
      with open('file_tmp/'+mingzi, 'wb') as f:
        f.write(r.content)
    f.close()


  def bisector_list(self,tabulation: list, num: int):
    """
    将列表平均分成几份
    :param tabulation: 列表
    :param num: 份数
    :return: 返回一个新的列表
    """
    new_list = []

    '''列表长度大于等于份数'''
    if len(tabulation) >= num:
      '''remainder:列表长度除以份数,取余'''
      remainder = len(tabulation) % num
      if remainder == 0:
        '''merchant:列表长度除以分数'''
        merchant = int(len(tabulation) / num)
        '''将列表平均拆分'''
        for i in range(1, num + 1):
          if i == 1:
            new_list.append(tabulation[:merchant])
          else:
            new_list.append(tabulation[(i - 1) * merchant:i * merchant])
        return new_list
      else:
        '''merchant:列表长度除以分数 取商'''
        merchant = int(len(tabulation) // num)
        '''remainder:列表长度除以份数,取余'''
        remainder = int(len(tabulation) % num)
        '''将列表平均拆分'''
        for i in range(1, num + 1):
          if i == 1:
            new_list.append(tabulation[:merchant])
          else:
            new_list.append(tabulation[(i - 1) * merchant:i * merchant])
            '''将剩余数据的添加前面列表中'''
            if int(len(tabulation) - i * merchant) <= merchant:
              for j in tabulation[-remainder:]:
                new_list[tabulation[-remainder:].index(j)].append(j)
        return new_list
    else:
      '''如果列表长度小于份数'''
      for i in range(1, len(tabulation) + 1):
        tabulation_subset = []
        tabulation_subset.append(tabulation[i - 1])
        new_list.append(tabulation_subset)
      return new_list

if __name__=='__main__':
  xiazai('http://iqiyi.cdn9-okzy.com/20200907/15137_ed25d8c5/index.m3u8')

速度很慢.  40m 5分钟  不加多线程 1小时。 可能我的m3u8不行,或者我电脑不行, 多线程是机械式的。  电脑好 可以多加几条。

以上就是python 下载m3u8视频的示例代码的详细内容,更多关于python 下载m3u8视频的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python Django批量导入数据
Mar 25 Python
python进行两个表格对比的方法
Jun 27 Python
使用Python读取二进制文件的实例讲解
Jul 09 Python
Python 实现Windows开机运行某软件的方法
Oct 14 Python
python实现关闭第三方窗口的方法
Jun 28 Python
python基于json文件实现的gearman任务自动重启代码实例
Aug 13 Python
Tensorflow 模型转换 .pb convert to .lite实例
Feb 12 Python
Python getsizeof()和getsize()区分详解
Nov 20 Python
浅谈Python基础之列表那些事儿
May 11 Python
Python中的变量与常量
Nov 11 Python
宝塔更新Python及Flask项目的部署
Apr 11 Python
python库Tsmoothie模块数据平滑化异常点抓取
Jun 10 Python
pytorch简介
Nov 11 #Python
Python远程linux执行命令实现
Nov 11 #Python
python 实现简单的计算器(gui界面)
Nov 11 #Python
python海龟绘图之画国旗实例代码
Nov 11 #Python
python 实现倒计时功能(gui界面)
Nov 11 #Python
windows+vscode安装paddleOCR运行环境的步骤
Nov 11 #Python
Django基于Models定制Admin后台实现过程解析
Nov 11 #Python
You might like
PHP set_time_limit(0)长连接的实现分析
2010/03/02 PHP
php数组保存文本与文本反编成数组实例
2014/11/13 PHP
PHP基于MySQL数据库实现对象持久层的方法
2015/06/17 PHP
PHP如何将XML转成数组
2016/04/04 PHP
php文件上传类完整实例
2016/05/14 PHP
Yii框架实现的验证码、登录及退出功能示例
2017/05/20 PHP
PHP实现无限极分类的两种方式示例【递归和引用方式】
2019/03/25 PHP
php计数排序算法的实现代码(附四个实例代码)
2020/03/31 PHP
js控制框架刷新
2008/08/01 Javascript
一个cssQuery对象 javascript脚本实现代码
2009/07/21 Javascript
JavaScript的setAttribute兼容性问题解决方法
2013/11/11 Javascript
javascript批量修改文件编码格式的方法
2015/01/27 Javascript
你所不了解的javascript操作DOM的细节知识点(一)
2015/06/17 Javascript
表单验证插件Validation应用的实例讲解
2015/10/10 Javascript
原生JavaScript制作微博发布面板效果
2016/03/11 Javascript
深入理解Ajax的get和post请求
2016/06/02 Javascript
JS图片左右无缝隙滚动的实现(兼容IE,Firefox 遵循W3C标准)
2016/09/23 Javascript
详谈js对url进行编码和解码(三种方式的区别)
2017/08/16 Javascript
[04:22]DOTA2上海特级锦标赛主赛事第四日TOP10
2016/03/06 DOTA
[43:14]Liquid vs Optic 2018国际邀请赛淘汰赛BO3 第二场 8.21
2018/08/22 DOTA
[03:12]完美世界DOTA2联赛PWL DAY7集锦
2020/11/06 DOTA
基于Python数据可视化利器Matplotlib,绘图入门篇,Pyplot详解
2017/10/13 Python
python导出hive数据表的schema实例代码
2018/01/22 Python
如何用Python合并lmdb文件
2018/07/02 Python
[原创]Python入门教程4. 元组基本操作
2018/10/31 Python
网易2016研发工程师编程题 奖学金(python)
2019/06/19 Python
基于Django静态资源部署404的解决方法
2019/07/28 Python
python中的函数递归和迭代原理解析
2019/11/14 Python
基于python实现对文件进行切分行
2020/04/26 Python
python绘制趋势图的示例
2020/09/17 Python
泰国汽车、火车和轮渡票预订网站:Bus Online Ticket
2017/09/09 全球购物
美国和加拿大计算机和电子产品购物网站:TigerDirect.com
2019/09/13 全球购物
卫生院健康教育实施方案
2014/06/07 职场文书
工厂门卫的岗位职责
2014/07/27 职场文书
审美与表现自我评价
2015/03/09 职场文书
2016年社会管理综治宣传月活动总结
2016/03/16 职场文书