python + streamlink 下载 vimeo 短视频
1. 起因, 目的:
- 看到一个视频,很喜欢,想下载。
- https://player.vimeo.com/video/937787642
2. 先看效果
能下载。
3. 过程:
- 因为我自己没头绪。先看一下别人的例子, 问一下 ai 或是 google
- 问了几个来回,原来是流式加载的视频。 那么好办, 就使用 streamlink , 之前用过,效果很好的。
下载
import requests
import streamlink
import osdef get_vimeo_stream_url(video_url):# 设置请求头,模拟浏览器headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36","Referer": "https://vimeo.com/"}try:# Step 1: 获取配置 JSONconfig_url = video_url.replace("player.vimeo.com/video/", "player.vimeo.com/video/") + "/config"response = requests.get(config_url, headers=headers)response.raise_for_status()# Step 2: 解析 JSON 数据config_data = response.json()# 优先提取 HLS 链接hls_url = config_data.get("request", {}).get("files", {}).get("hls", {}).get("cdns", {}).get("akfire_interconnect_quic", {}).get("url")if not hls_url:hls_url = config_data.get("request", {}).get("files", {}).get("hls", {}).get("cdns", {}).get("fastly",{}).get("url")if hls_url:print(f"找到 HLS 链接: {hls_url}")return hls_url# 如果没有 HLS,尝试提取 progressive(MP4)链接video_files = config_data.get("request", {}).get("files", {}).get("progressive", [])if video_files:video_files = sorted(video_files, key=lambda x: x.get("height", 0), reverse=True)mp4_url = video_files[0]["url"]print(f"没有 HLS 链接,使用 MP4 链接: {mp4_url}")return mp4_urlprint("未找到可用的流链接!可能是受限视频或需要登录。")return Noneexcept requests.exceptions.RequestException as e:print(f"请求错误: {e}")return Noneexcept (KeyError, IndexError) as e:print(f"解析错误: {e},可能是视频受限或格式不正确")return Nonedef download_with_streamlink(stream_url, output_path="video.mp4"):try:# Step 3: 使用 streamlink 下载streams = streamlink.streams(stream_url)if not streams:print("无法获取视频流,可能是链接无效或需要认证")return False# 选择最佳质量stream = streams.get("best")if not stream:print("未找到最佳质量流")return Falseprint(f"开始下载,质量: {stream}")with stream.open() as stream_data:with open(output_path, "wb") as f:while True:data = stream_data.read(8192)if not data:breakf.write(data)print(f"视频已下载到: {output_path}")return Trueexcept Exception as e:print(f"下载错误: {e}")return False# 示例使用
video_url = "https://player.vimeo.com/video/937787642"
output_file = "downloaded_video.mp4"# 获取流链接
stream_url = get_vimeo_stream_url(video_url)
if stream_url:# 使用 streamlink 下载download_with_streamlink(stream_url, output_file)
4. 结论 + todo
-
想法: 下载其他视频, 或是批量下载。但是我觉得没意思。
-
我就是想试试看能不能下载成功。
-
聊天记录: https://x.com/i/grok?conversation=1923401591656530204
-
vimeo 简介: https://chatgpt.com/c/68275b18-7d68-8002-9197-a84a62128cab
希望对大家有帮助。