You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取YouTube视频的相关视频?(替代YouTube Data API已弃用参数)

解决方案:获取YouTube相关视频(替代已弃用的relatedToVideoId)

一、使用YouTube Data API的可行方案

虽然relatedToVideoId参数已被移除,但可以通过组合调用API接口实现需求:

  1. 第一步:获取目标视频的核心元数据
    调用Videos.list接口,传入目标视频ID,请求id, snippet字段,提取视频的categoryId(分类ID)和snippet.tags(标签),也可从标题、描述中提取核心关键词。
  • PHP示例:
$apiKey = '你的API密钥';
$videoId = '目标视频ID';
$url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=$videoId&key=$apiKey";

$response = file_get_contents($url);
$data = json_decode($response, true);
$categoryId = $data['items'][0]['snippet']['categoryId'];
$tags = $data['items'][0]['snippet']['tags'];
$keywords = implode(' ', $tags); // 以标签作为搜索关键词
  • JavaScript示例(建议通过服务端代理调用API,避免密钥泄露):
const apiKey = '你的API密钥';
const videoId = '目标视频ID';
fetch(`https://www.googleapis.com/youtube/v3/videos?part=snippet&id=${videoId}&key=${apiKey}`)
  .then(res => res.json())
  .then(data => {
    const categoryId = data.items[0].snippet.categoryId;
    const tags = data.items[0].snippet.tags;
    const keywords = tags.join(' ');
    // 执行下一步搜索
  });
  1. 第二步:搜索同类目同内容的视频
    调用Search.list接口,配置以下关键参数:
  • type=video:仅返回视频结果

  • q=提取的关键词:用第一步获取的标签或自定义关键词

  • videoCategoryId=目标视频的categoryId:限定视频分类

  • maxResults=n:设置需要返回的视频数量

  • 可选:relevanceLanguage(指定语言)、publishedAfter(过滤发布时间)等

  • PHP示例:

$searchUrl = "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=$keywords&videoCategoryId=$categoryId&maxResults=10&key=$apiKey";
$searchResponse = file_get_contents($searchUrl);
$relatedVideos = json_decode($searchResponse, true);
// 处理返回的相关视频数据
  • JavaScript示例:
fetch(`https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=${keywords}&videoCategoryId=${categoryId}&maxResults=10&key=${apiKey}`)
  .then(res => res.json())
  .then(relatedData => {
    // 处理相关视频列表
  });

二、非API的替代方案

如果不使用官方Data API,可考虑以下方式,但需注意风险:

  • 解析YouTube视频页面HTML:直接请求目标视频的网页,解析页面中「相关视频」区块的DOM结构,提取视频ID和信息。但YouTube页面结构频繁变更,且可能触发反爬机制,违反其服务条款,稳定性较差。
  • 第三方数据服务:部分第三方平台提供YouTube视频数据的封装接口,但需确认服务的合法性与稳定性,避免依赖不可靠资源。

内容的提问来源于stack exchange,提问作者WB_Research

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 06:05:29