You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何获取YouTube剪辑片段的起始点、结束点及关联原视频信息

如何获取YouTube剪辑片段的起始点、结束点及关联原视频信息

我之前也碰到过这个问题,YouTube Clip的URL确实完全不直观,看不到任何和原视频、时间点相关的线索。不过有两种比较靠谱的方法可以获取你需要的信息,我给你详细说说:

一、通过页面内嵌JSON提取(无需API密钥)

YouTube的网页其实会把剪辑的核心数据藏在页面的<script>标签里的JSON结构中,比你找到的ytd-watch-flexy标签更直接。你可以找包含window["ytInitialPlayerResponse"]的script块,里面的播放器响应数据里就有所有你要的信息。

给你写个Python示例代码,用requestsBeautifulSoup来实现:

import requests
import json
from bs4 import BeautifulSoup

# 替换成你要解析的Clip URL
clip_url = "https://youtube.com/clip/UgkxU2HSeGL_NvmDJ-nQJrlLwllwMDBdGZFs"

# 获取页面内容
response = requests.get(clip_url)
soup = BeautifulSoup(response.text, "html.parser")

# 定位包含播放器初始化数据的script标签
player_response = None
for script in soup.find_all("script"):
    script_content = script.string
    if script_content and "ytInitialPlayerResponse" in script_content:
        # 提取JSON部分(处理一下字符串格式)
        start_mark = "ytInitialPlayerResponse = "
        start_idx = script_content.find(start_mark) + len(start_mark)
        end_idx = script_content.find("};", start_idx) + 1
        player_response = json.loads(script_content[start_idx:end_idx])
        break

if player_response:
    # 提取关键信息
    video_id = player_response["videoDetails"]["videoId"]
    start_time = player_response["playbackStartMs"] / 1000  # 毫秒转秒
    end_time = player_response["playbackEndMs"] / 1000
    duration = end_time - start_time

    print(f"原视频ID: {video_id}")
    print(f"起始时间: {start_time}秒")
    print(f"结束时间: {end_time}秒")
    print(f"剪辑时长: {duration}秒")
else:
    print("未能找到播放器初始化数据,可能页面结构已更新")

这个方法不需要API密钥,适合快速获取数据,但要注意YouTube的页面结构可能会不定期更新,导致解析逻辑失效。

二、使用YouTube Data API(长期稳定方案)

如果需要长期稳定的获取剪辑信息,官方的YouTube Data API是更好的选择,它专门提供了剪辑相关的查询接口。

操作步骤:

  1. 先去Google Cloud Console创建一个项目,启用YouTube Data API v3,然后生成一个API密钥(免费额度足够大部分个人使用)。
  2. 使用Clips.list接口,传入剪辑的ID(就是Clip URL里Ugkx后面的32位字符,比如你的例子里是U2HSeGL_NvmDJ-nQJrlLwllwMDBdGZFs)。

Python代码示例(需要先安装google-api-python-client):

pip install google-api-python-client
from googleapiclient.discovery import build

# 替换成你的API密钥
API_KEY = "你的Google API密钥"
# 替换成你要查询的Clip ID
clip_id = "U2HSeGL_NvmDJ-nQJrlLwllwMDBdGZFs"

# 构建API客户端
youtube = build('youtube', 'v3', developerKey=API_KEY)

# 调用Clips.list接口获取剪辑信息
request = youtube.clips().list(
    part="contentDetails,snippet",
    id=clip_id
)
response = request.execute()

# 解析返回结果
if response.get("items"):
    clip_info = response["items"][0]
    content_details = clip_info["contentDetails"]
    
    video_id = content_details["videoId"]
    start_time = content_details["startTimeSeconds"]
    end_time = content_details["endTimeSeconds"]
    duration = float(end_time) - float(start_time)

    print(f"原视频ID: {video_id}")
    print(f"起始时间: {start_time}秒")
    print(f"结束时间: {end_time}秒")
    print(f"剪辑时长: {duration}秒")
else:
    print("未找到该剪辑的相关信息,请检查Clip ID是否正确")

这个方法的优势是官方维护,数据结构稳定,不会因为页面更新而失效,唯一需要注意的是API有调用配额限制,不过免费额度完全能满足普通需求。

备注:内容来源于stack exchange,提问作者futium

火山引擎 最新活动