请求下载 Python 中的视频

Make a request to download a video in Python

我有 link 个表格:

http://youtubeinmp3.com/fetch/?video=LINK_TO_YOUTUBE_VIDEO_HERE

如果您将 link 这种类型的文件放入网页的 <a> 标签中,单击它们将下载 link 末尾的 YouTube 视频的 MP3。来源是 here.

我想通过发出 post 请求(或类似的东西)从命令行模仿这个过程,但我不确定如何在 Python 中做到这一点!请给我任何建议,或者这比我想象的要难吗?

在其API Doc, it provides one version of URL which returns download link as JSON: http://youtubeinmp3.com/fetch/?api=advanced&format=JSON&video=http://www.youtube.com/watch?v=i62Zjga8JOM

Ok 然后我们可以使用 urllib2 调用 API 并获取 API 结果,然后使用 json.loads() 反序列化,并再次使用 urllib2 下载 mp3 文件。

import urllib2
import json

r = urllib2.urlopen('http://youtubeinmp3.com/fetch/?api=advanced&format=JSON&video=http://www.youtube.com/watch?v=i62Zjga8JOM')
content = r.read()
# extract download link
download_url = json.loads(content)['link']
download_content = urllib2.urlopen(download_url).read()
# save downloaded content to file
f = open('test.mp3', 'wb')
f.write(download_content)
f.close()

注意文件应该使用模式'wb'打开,否则无法正确播放mp3文件。 如果文件很大,下载将是一个耗时的过程。这里有一个 post 描述如何 display downloading progress in GUI (PySide)

作为Mark Ma mentioned, you can get it done without leaving the standard library by utilizing urllib2. I like to use Requests,所以我做了这个:

import os
import requests

dump_directory = os.path.join(os.getcwd(), 'mp3')
os.makedirs(dump_directory, exist_ok=True)


def dump_mp3_for(resource):
    payload = {
        'api': 'advanced',
        'format': 'JSON',
        'video': resource
    }
    initial_request = requests.get('http://youtubeinmp3.com/fetch/', params=payload)
    if initial_request.status_code == 200:  # good to go
        download_mp3_at(initial_request)


def download_mp3_at(initial_request):
    j = initial_request.json()
    filename = '{0}.mp3'.format(j['title'])
    r = requests.get(j['link'], stream=True)
    with open(os.path.join(dump_directory, filename), 'wb') as f:
        print('Dumping "{0}"...'.format(filename))
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()

然后遍历 YouTube 视频链接列表并将它们一个接一个地传递到 dump_mp3_for()

for video in ['http://www.youtube.com/watch?v=i62Zjga8JOM']:
    dump_mp3_for(video)

如果您想从 YouTube 下载视频或音频,您可以使用此模块pytube它会完成所有艰苦的工作。

您也可以只列出音频:

from pytube import YouTube

# initialize a YouTube object by the url
yt = YouTube("YOUTUBE_URL")

# that will get all audio files available
audio_list = yt.streams.filter(only_audio=True).all()
print(audio_list)  

然后下载:

# that will download the file to current working directory
yt.streams.filter(only_audio=True)[0].download()

完整代码:

from pytube import YouTube
yt = YouTube ("YOUTUBE_URL")
audio = yt.streams.filter(only_audio=True).first()
audio.download()