【问题标题】:Make a request to download a video in Python发出请求以使用 Python 下载视频
【发布时间】:2015-05-31 17:11:59
【问题描述】:

我有以下形式的链接:

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

如果您将这种类型的链接放在网页上的 <a> 标记中,点击它们会在链接末尾下载 YouTube 视频的 MP3。来源是here

我想通过发出 post 请求(或类似的东西)从命令行模拟这个过程,但我不知道如何在 Python 中做到这一点!请问我可以得到任何建议,还是这比我想象的更难?

【问题讨论】:

  • 标准库中有一个函数可以做到这一点。
  • 太棒了。有什么作用?

标签: python http-post


【解决方案1】:

正如Mark Ma 提到的,您可以使用urllib2 在不离开标准库的情况下完成它。我喜欢用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)

【讨论】:

  • 您的编辑不正确。 Python 2 还支持with 上下文管理器。
  • 我没有意识到这一点。固定。
【解决方案2】:

在其API Doc 中,它提供了一种以 JSON 格式返回下载链接的 URL 版本: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 文件。 如果文件很大,下载将是一个耗时的过程。这里有一篇文章描述了如何display downloading progress in GUI (PySide)

【讨论】:

    【解决方案3】:

    如果您想从 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()
    

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多