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实现对比不同字体中的同一字符的显示效果
Apr 23 Python
Ruby使用eventmachine为HTTP服务器添加文件下载功能
Apr 20 Python
Python的Django中将文件上传至七牛云存储的代码分享
Jun 03 Python
Python 网页解析HTMLParse的实例详解
Aug 10 Python
python中import与from方法总结(推荐)
Mar 21 Python
Python GUI编程完整示例
Apr 04 Python
浅谈Python_Openpyxl使用(最全总结)
Sep 05 Python
原来我一直安装 Python 库的姿势都不对呀
Nov 11 Python
几款好用的python工具库(小结)
Oct 20 Python
浅析Python模块之间的相互引用问题
Feb 26 Python
Python基础之赋值,浅拷贝,深拷贝的区别
Apr 30 Python
python使用shell脚本创建kafka连接器
Apr 29 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
dedecms防止FCK乱格式化你的代码的修改方法
2007/03/17 PHP
ThinkPHP+EasyUI之ComboTree中的会计科目树形菜单实现方法
2017/06/09 PHP
PHP实现模拟http请求的方法分析
2017/12/20 PHP
PHP实现SMTP邮件的发送实例
2018/09/27 PHP
多广告投放代码 推荐
2006/11/13 Javascript
jQuery Tips 为AJAX回调函数传递额外参数的方法
2010/12/28 Javascript
地址栏传递中文参数乱码在js里用escape转码
2013/08/28 Javascript
jquery使用append(content)方法注意事项分享
2014/01/06 Javascript
一个很有趣3D球状标签云兼容IE8
2014/08/22 Javascript
JavaScript strike方法入门实例(给字符串加上删除线)
2014/10/17 Javascript
jQuery中closest()函数用法实例
2015/01/07 Javascript
浅析AngularJS中的生命周期和延迟处理
2015/06/18 Javascript
果断收藏9个Javascript代码高亮脚本
2016/01/06 Javascript
jQuery遍历DOM节点操作之filter()方法详解
2016/04/14 Javascript
jquery操作select取值赋值与设置选中实例
2017/02/28 Javascript
在vue.js中抽出公共代码的方法示例
2017/06/08 Javascript
JavaScript数据结构与算法之二叉树遍历算法详解【先序、中序、后序】
2019/02/21 Javascript
NodeJS实现同步的方法
2019/03/02 NodeJs
使用Vue调取接口,并渲染数据的示例代码
2019/10/28 Javascript
vue-router之实现导航切换过渡动画效果
2019/10/31 Javascript
vue实现两个组件之间数据共享和修改操作
2020/11/12 Javascript
vue3.0+vue-router+element-plus初实践
2020/12/02 Vue.js
Python3指定路径寻找符合匹配模式文件
2015/05/22 Python
基于python历史天气采集的分析
2019/02/14 Python
Python3使用TCP编写一个简易的文件下载器功能
2019/05/08 Python
Python代码块及缓存机制原理详解
2019/12/13 Python
python中count函数简单的实例讲解
2020/02/06 Python
python except异常处理之后不退出,解决异常继续执行的实现
2020/04/25 Python
Python如何将函数值赋给变量
2020/04/28 Python
香港草莓网:Strawberrynet香港
2019/05/10 全球购物
KIKO MILANO俄罗斯官网:意大利领先的化妆品和护肤品品牌
2021/01/09 全球购物
速卖通欧盟:Aliexpress EU
2020/08/19 全球购物
EJB的几种类型
2012/08/15 面试题
简历中个人求职的自我评价模板
2013/11/29 职场文书
2019个人半年工作总结
2019/06/21 职场文书
分享MySQL常用 内核 Debug 几种常见方法
2022/03/17 MySQL