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 Mysql数据库操作 Perl操作Mysql数据库
Jan 12 Python
python通过pil将图片转换成黑白效果的方法
Mar 16 Python
python检查字符串是否是正确ISBN的方法
Jul 11 Python
python3设计模式之简单工厂模式
Oct 17 Python
Python中最大递归深度值的探讨
Mar 05 Python
Python占用的内存优化教程
Jul 28 Python
pytorch 自定义数据集加载方法
Aug 18 Python
python如何获取apk的packagename和activity
Jan 10 Python
40行Python代码实现天气预报和每日鸡汤推送功能
Feb 27 Python
python可以用哪些数据库
Jun 22 Python
使用tensorflow进行音乐类型的分类
Aug 14 Python
python如何实现递归转非递归
Feb 25 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
fleaphp crud操作之findByField函数的使用方法
2011/04/23 PHP
深入分析使用mysql_fetch_object()以对象的形式返回查询结果
2013/06/05 PHP
php二维数组排序详解
2013/11/06 PHP
php中把美国时间转为北京时间的自定义函数分享
2014/07/28 PHP
ThinkPHP后台首页index使用frameset时的注意事项分析
2014/08/22 PHP
thinkphp3.2.3 分页代码分享
2016/07/28 PHP
YII2框架中使用yii.js实现的post请求
2017/04/09 PHP
对于Laravel 5.5核心架构的深入理解
2018/02/22 PHP
CI框架网页缓存简单用法分析
2018/12/26 PHP
javascript 全等号运算符使用说明
2010/05/31 Javascript
解决jquery的.animate()函数在IE6下的问题
2010/12/03 Javascript
node.js中的fs.truncateSync方法使用说明
2014/12/15 Javascript
通过Jquery.cookie.js实现展示浏览网页的历史记录超管用
2015/10/23 Javascript
javascript实现一个简单的弹出窗
2016/02/22 Javascript
asp.net+jquery.form实现图片异步上传的方法(附jquery.form.js下载)
2016/05/05 Javascript
HTML5+jQuery插件Quicksand实现超酷的星际争霸2兵种分类展示效果(附demo源码下载)
2016/05/25 Javascript
关于iframe跨域POST提交的方法示例
2017/01/15 Javascript
基于Node.js的WebSocket通信实现
2017/03/11 Javascript
浅谈关于angularJs中使用$.ajax的注意点
2017/08/12 Javascript
你应该知道的几类npm依赖包管理详解
2017/10/06 Javascript
MVVM框架下实现分页功能示例
2018/06/14 Javascript
手动下载Chrome并解决puppeteer无法使用问题
2018/11/12 Javascript
angular 实现同步验证器跨字段验证的方法
2019/04/11 Javascript
Javascript数组及类数组相关原理详解
2020/10/29 Javascript
微信小程序视频弹幕发送功能的实现
2020/12/28 Javascript
Python简单生成随机姓名的方法示例
2017/12/27 Python
Python统计单词出现的次数
2018/04/04 Python
python用requests实现http请求代码实例
2019/10/31 Python
python调用接口的4种方式代码实例
2019/11/19 Python
pycharm 如何取消连按两下shift出现的全局搜索
2021/01/15 Python
基于HTML5 Canvas:字符串,路径,背景,图片的详解
2013/05/09 HTML / CSS
贸易经济专业自荐书
2014/06/29 职场文书
教师竞聘上岗演讲稿
2014/09/03 职场文书
信用卡催款律师函
2015/05/27 职场文书
HTML+css盒子模型案例(圆,半圆等)“border-radius” 简单易上手
2021/05/10 HTML / CSS