youtube-dl 下载视频

youtube-dl 下载视频

摘要

youtube-dl 下载视频

依赖转码工具

ubuntu14.04 下安装ffmpeg

sudo apt-get install python-software-properties
sudo apt-add-repository ppa:mc3man/trusty-media
sudo apt-get update
sudo apt-get install ffmpeg gstreamer0.10-ffmpeg

ubuntu14.04 下安装avconv

sudo add-apt-repository ppa:heyarje/libav-11 && sudo apt-get update
sudo apt-get install libav-tools

安装youtube-dl

pip install youtube-dl

python脚本下载视频

主要作用是获取进行的状态到 xxx/log.txt

是否正在下载,是否下载完成了(视频/音频) ,正在合并以及合并完成.

执行 python 111.py https://www.youtube.com/watch?v=lAaCeiqE6CE xxx 即可下载指定的视频.
然后被存储在 xxx 文件夹下.

sys.argv[1] 才是第一个参数
sys.argv[0] 是文件本身的文件名,这里就是111.py

111.py内容如下

编辑器的问题, 可能空格 tab被忽略, 影响python代码的正确性.
建议访问正确的代码 看这里—> https://github.com/daodaovps/youtube-dl-py

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from __future__ import unicode_literals
import youtube_dl
import os
import sys
import time
import shutil

reload(sys)
sys.setdefaultencoding('utf-8')

def getnow():
        return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
def  delfile(filename):
    if os.path.exists(filename):
        os.remove(filename)

if len(sys.argv)!=3 :
        print ("invalid  args ;  downvideo.py {url} {savefolder}")
        exit()
#downurl="https://www.youtube.com/watch?v=i5IqVSOI3Ug"
#savepath="video-save"
downurl=sys.argv[1] 
savepath=sys.argv[2]

if os.path.exists(savepath):
    shutil.rmtree(savepath)
os.mkdir(savepath)

logfilename=savepath+"/"+'log.txt'
logfile=open(logfilename,'a')
logfile.write(getnow()+"\tbegin-download\t"+downurl+"\t"+savepath+"\n")

class MyLogger(object):
    def debug(self, msg):
        pass
    def warning(self, msg):
        pass
    def error(self, msg):
        print(msg)

def my_hook(d):

#    print("\r\nfilename "+d['filename']+"\r\n")
#    print("tmpfilename "+d['tmpfilename'])
#    print("downloaded_bytes "+str(d['downloaded_bytes']))
#    print("total_bytes "+ str(d['total_bytes']))
#    print("total_bytes_estimate "+ str(d['total_bytes_estimate']))
#    print("elapsed "+ str(d['elapsed']))
#    print("eta "+ str(d['eta']))
#    print("speed "+ str(d['speed']+"\r\n"))


    if d['status'] == 'finished':
        print('download 100%')
    logfile.write(getnow()+"\tdownloaded\n")
    if str(d['filename']).endswith('.m4a') :
        logfile.write(getnow()+"\talldownloaded\tthen merging\n")
        logfile.close()
    else :
    print(d["status"]+" "+d["filename"])
    logfile.write(getnow()+"\t"+d['status']+"\t"+d['filename']+"\n")


ydl_opts = {
    # 'proxy': 'http://123.153.123.24:808',
    # 'proxy':'http://127.0.0.1:8123',
    # 'proxy':'socks5://127.0.0.1:1080',
    #%(title)s-%(id)s.%(ext)s
    'outtmpl' : savepath+"/"+'saved.%(ext)s' ,
    'writeinfojson': 'true`',
    'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio',
    'recode_video' :'mp4',
    'merge_output_format': 'mp4',
    'ignoreerrors': 'true',
    #'keepvideo': 'false',  
    # 'noplaylist': 'true', # default = true 
    # 'logger': MyLogger(),
    'progress_hooks': [my_hook],
    'postprocessors': [{
        'key': 'ExecAfterDownload',
        'exec_cmd': "echo \""+getnow()+"\tmerge-end\" >> xxx/log.txt || exit 0; ls "
    }]
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download([downurl])
    # ydl.download(['https://www.youtube.com/watch?v=KaKq0UUTPU0&list=PLywfaJMr2okmMx9Ntlqq2YaEf7FQ8byq1'])