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
希望對大家有幫助。