下载 m3u8 视频脚本

此文版权属于作者所有,任何人、媒体或者网站转载、借用都必须征得作者本人同意!

直接上代码,python 的:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright 2016 [email protected]

import contextlib
import os
import sys
import urllib2
import urlparse

def remove(path):
    try:
        os.remove(path)
    except:
        pass

def mkdir(path):
    try:
        os.mkdir(path)
    except:
        pass

def download(fname, url):
  print u'下载', fname
  print ' ', url

  with contextlib.closing(urllib2.urlopen(url)) as x:
    handle = open(fname, 'w')
    handle.write(x.read())
    handle.close()
    redirect_url = x.geturl()
    return redirect_url

  return url


def download_m3u8(url):
  base_url = url

  tmp_fname = '.tmp.m3u8'
  remove(tmp_fname)

  base_redirect_url = download(tmp_fname, base_url)

  with open(tmp_fname) as fi:
    fid = 1
    mkdir('ts')
    with open('01.m3u8', 'w') as fo:
      for line in fi:
        sline = line.strip()
        if sline and len(sline) > 1 and not sline.startswith('#'):
          fn = 'ts%s%03d.ts' % (os.sep, fid)
          fid = fid + 1
          fo.write(fn)
          fo.write('\r\n')
          sub_url = urlparse.urljoin(base_redirect_url, sline)
          print u'尝试下载', sline
          download(fn, sub_url)
        else:
          fo.write(line)

  remove(tmp_fname)

def usage():
  print 'usage:'
  print ' ', os.path.basename(sys.argv[0]), 'url'

def main():
  if len(sys.argv) <= 1:
    usage()
  else:
    download_m3u8(sys.argv[1])

if __name__ == "__main__":
    main()

todo:

1. add UserAgent and cookie to request

2. support sub m3u8


你可能感兴趣的:(其他)