网易云课堂视频下载

1 通过网络分析找到视频的网址

 

网易云课堂视频下载_第1张图片

 

2源代码如下:

import requests
import os

import optparse


headers = {
    "User - Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 84.0.4147.105 Safari / 537.36"
    }

def down_load_ts(url,pathname):
    basepath = os.path.join(os.getcwd(),pathname)
    if not os.path.exists(basepath):
        os.mkdir(basepath)


    try:
        req = requests.get(url,headers=headers)
        #print(req.text)
        file_line_list = req.text.split('\n')
        if not "#EXTM3U" in file_line_list[0]:
            raise BaseException(u'非M3U8的连接')
        else:
            unknow = True
            file_index=100000
            for index,line in enumerate(file_line_list):
                if "#EXTINF" in line:
                    unknow = False
                    url_ts = str(url).rsplit('/',1)[0] +'/'+ str(file_line_list[index+1])
                    #下载文件名重新编号,以防合并是造成文件顺序混乱
                    file_name = str(file_index)+'.ts'
                    file_index+=1
                    full_file_name =os.path.join(basepath,file_name)
                    # print(url_ts)

                    process_ts(url_ts, full_file_name)

                    

            if unknow:
                raise BaseException('未找到对应的下载连接')
            else:
                
                print(pathname,':downloaded')
                print("start merge file to mp4")
                mergeFileToMP4(pathname)
                return


    except Exception as e:
        print(e)
        return

def process_ts(url_ts,full_file_name):
    
     req_ts = requests.get(url_ts, headers=headers)
     print("downloading file:", os.path.split(full_file_name)[1])
     with open(full_file_name, 'ab') as fw:
         fw.write(req_ts.content)
         fw.flush()


def mergeFileToMP4(pathname):
    os.chdir(os.path.join(os.getcwd(),pathname))
    cmd = "copy /b * new.tmp"
    os.system(cmd)
    os.system('del /Q *.ts')
    os.system('del /Q *.mp4')
    os.rename("new.tmp", "new.mp4")
    print("merge file is :",str(os.path.join(os.getcwd(),pathname,"new.mp4")))


def main():
    # parser = optparse.OptionParser("usage -n  -u  -h \n")
    # parser.add_option('-n',dest = "pathname",type ="string",help="specify a save path name")
    # parser.add_option('-u',dest='url',type='string',help="specify a m3u8 url")
    # (options,args)= parser.parse_args()
    # pathname = options.pathname
    # url = options.url
    # if (pathname ==None) or (url == None):
    #     print(parser.usage)
    #     return
    url = 'https://jdvodluwytr3t.1217106454_a7850079a3ed43f29c6f4169201b4893_sd.m3u8?'
    pathname = '163nixiang-1'
    
    down_load_ts(url=url,pathname=pathname)


if __name__ == '__main__':
    main()

 

注:在ts文件进行合并为mp4文件时没有问题,但合成的文件就不能播放,通过多次测试发现,是下载的ts文件因为文件名拍讯的问题,例如 d99.ts  d100.ts d990.ts 三个文件,在进行合并是,d99.ts 会排在100之后跟d990.ts一起,因此对下载文件重新进行了编号,问题解决。

你可能感兴趣的:(语言,python)