首页 > 解决方案 > 如何以编程方式下载 Python 中 blob 中引用的 m3u8 视频?

问题描述

请注意,这个问题与How do we download a blob url video [关闭]不同,因为它不需要与浏览器进行人工交互

我有以下问题:

我需要做什么:

请注意,该解决方案不需要与浏览器进行人工交互。API 方面,输入应该是 URL 列表,输出应该是视频/gif 列表。

如果您想测试您的解决方案,可以在此处找到示例页面。

我的理解是我可以使用 Selene 来获取 HTML 并点击图片来启动播放器。但是,我不知道如何处理 blob 以获取 m3u8,然后将其用于实际视频。

标签: pythonweb-scrapingbeautifulsoupm3u8m3u

解决方案


稍加挖掘,您无需单击任何按钮。当您单击按钮时,它会调用 master.m3u8 文件。使用开发工具,您可以拼凑请求的 url。问题是,第一个文件不包含指向实际视频的链接。您拼凑另一个请求以获得最终的 m3u8 文件。从那里,您可以使用其他 SO 链接下载视频。它是分段的,因此不是直接下载。您可以取消注释下面的打印语句,查看每个 m3u8 文件包含的内容。这也将循环浏览页面

 import re
 for i in range(6119, 6121):
    url = 'https://www2.nhk.or.jp/signlanguage/sp/enquete.cgi?dno={}'.format(str(i))
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    print(soup.find(onclick=re.compile('signlanguage/movie'))) # locate the div that has the data we need

    video_id = soup.find(onclick=re.compile('signlanguage/movie')).get('onclick').split(',')[1].replace("'","")
    m3u8_url = 'https://nhks-vh.akamaihd.net/i/signlanguage/movie/v4/{}/{}.mp4/master.m3u8'.format(video_id[-1], video_id)
    # this m3u8 file doesn't contain download links, the next one does; so download and save that one
    r = requests.get(m3u8_url)
    # print(r.text)
 
    m3u8_url_2 = r.text.split('\n')[2] # get first link; high bandwidth
    r2 = requests.get(m3u8_url_2)
    # print(r2.text)
        
    # there are other ways to download the file, i'm just creating a new one with the data read and writing to a file
    fn = video_id + '.m3u8'
    with open(fn, 'w+') as f:
        f.write(r2.text)
        f.close()

推荐阅读