【问题标题】:How do I get the title of a youtube video if I have the Video Id?如果我有视频 ID,如何获得 youtube 视频的标题?
【发布时间】:2009-11-19 00:55:36
【问题描述】:

我现在正在玩 Youtube API,并开始了一个小项目(为了好玩)。

问题是我找不到从 ID 获取视频标题的方法。 (例如:ylLzyHk54Z0)

我查看了 DATA 和 PLAYER api 文档,但找不到。

如果有人知道如何做到这一点,或者如果有人可以帮助我找到做到这一点的方法,请帮助我。

注意:我使用的是 javascript。它将是一个网络应用程序。

编辑:我有一个想法。也许使用正则表达式从页面标题中解析出标题。我正在努力。

【问题讨论】:

  • 不要为此使用 RegEx 或屏幕截图! API 为您完成这一切......

标签: javascript api youtube title


【解决方案1】:

在 javascript 中不完全可能,因为您试图从不同的域获取文档。如果你愿意投入一点 php 试试这个。测试正常:

<?
    $vidID = $_POST['vidID'];
    $url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
    $doc = new DOMDocument;
    $doc->load($url);
    $title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
?>

<html>
    <head>
        <title>Get Video Name</title>
    </head>
    <body>
        <form action="test.php" method="post">
            <input type="text" value="ID Here" name="vidID" />
            <input type="submit" value="Get Name" />
        </form>
        <div id="page">URL: [<?= $url ?>]</div>
        <div id="title">Title: [<?= $title ?>]</div>
    </body>
</html>

【讨论】:

  • 感谢您的回答。是的,PHP 不是问题。我已经为 ajax 解决方案做好了准备。
  • 是的,其中一些可以在 javascript 中以不同的方式完成,但您仍然会遇到跨域问题,并且不需要让它变得比它必须的复杂。如果你高兴我希望你能接受答案:)
  • 只是一个更新,现在应该可以使用 JavaScript using the callback parameter
  • 同意@Marcel - 如果你使用JSONP(他的意思是使用回调参数),你可以进行跨域请求。
  • 它不再可用。
【解决方案2】:

这就是您可以使用 JavaScript 和 V3 YouTube 数据 API 实现的方法。

var ytApiKey = "...";
var videoId = "ylLzyHk54Z0";

$.get("https://www.googleapis.com/youtube/v3/videos?part=snippet&id=" + videoId + "&key=" + ytApiKey, function(data) {
  alert(data.items[0].snippet.title);
});

【讨论】:

  • 如何从视频标题中获取视频ID?
  • 这是API v3之后新的正确答案。
  • 我正在获取 CORS。有什么建议吗?
【解决方案3】:

您可以使用 JSON 请求:http://gdata.youtube.com/feeds/api/videos/ylLzyHk54Z0?v=2&amp;alt=jsonc

【讨论】:

    【解决方案4】:

    致电http://gdata.youtube.com/feeds/api/videos/ylLzyHk54Z0

    在此 XML 文件中,读取 &lt;title&gt; 标记的值。

    YouTube Api Documentation

    【讨论】:

      【解决方案5】:

      截至 2015 年 12 月,此答案是准确的。

      要从 YouTube 视频 ID 获取视频标题,您必须使用 YouTube 数据 API 构建以下 URL(您需要使用 API 密钥,否则请求将失败):

      https://www.googleapis.com/youtube/v3/videos?part=snippet&amp;id={YOUTUBE_VIDEO_ID}&amp;fields=items(id%2Csnippet)&amp;key={YOUR_API_KEY}

      执行 GET 请求,您将获得类似于以下块的 JSON 响应。对于标题,它存在于snippet/title 键中。

      {
         "items":[
            {
               "id":"Jglv0A0qLI8",
               "snippet":{
                  "publishedAt":"2014-06-30T03:42:20.000Z",
                  "channelId":"UCdTU5vd37FlTZ-xoB0xzRDA",
                  "title":"AIA Malaysia - A-Plus Venus Plan - Comprehensive Female Protection and Insurance Plan",
                  "description":"A comprehensive female protection plan for the modern women\n\nFor more information visit: http://www.aia.com.my/en/individuals/products-and-services/health/a-plus-venus-a-plus-venus-extra.html\n\nFor more products, visit AIA Malaysia's Products and Services playlist:\nhttps://www.youtube.com/playlist?list=PLSrgVT3aQ1fZ3SCe-dEVnFJDApBYkqolP\n\nFor more videos. subscribe to AIA Malaysia's YouTube channel:\nhttps://www.youtube.com/channel/UCdTU5vd37FlTZ-xoB0xzRDA",
                  "thumbnails":{
                     "default":{
                        "url":"https://i.ytimg.com/vi/Jglv0A0qLI8/default.jpg",
                        "width":120,
                        "height":90
                     },
                     "medium":{
                        "url":"https://i.ytimg.com/vi/Jglv0A0qLI8/mqdefault.jpg",
                        "width":320,
                        "height":180
                     },
                     "high":{
                        "url":"https://i.ytimg.com/vi/Jglv0A0qLI8/hqdefault.jpg",
                        "width":480,
                        "height":360
                     },
                     "standard":{
                        "url":"https://i.ytimg.com/vi/Jglv0A0qLI8/sddefault.jpg",
                        "width":640,
                        "height":480
                     },
                     "maxres":{
                        "url":"https://i.ytimg.com/vi/Jglv0A0qLI8/maxresdefault.jpg",
                        "width":1280,
                        "height":720
                     }
                  },
                  "channelTitle":"AIA Malaysia",
                  "tags":[
                     "aia",
                     "aia malaysia",
                     "a-plus venus",
                     "female health insurance",
                     "female life insurance",
                     "female insurance",
                     "female medical insurance"
                  ],
                  "categoryId":"27",
                  "liveBroadcastContent":"none",
                  "localized":{
                     "title":"AIA Malaysia - A-Plus Venus Plan - Comprehensive Female Protection and Insurance Plan",
                     "description":"A comprehensive female protection plan for the modern women\n\nFor more information visit: http://www.aia.com.my/en/individuals/products-and-services/health/a-plus-venus-a-plus-venus-extra.html\n\nFor more products, visit AIA Malaysia's Products and Services playlist:\nhttps://www.youtube.com/playlist?list=PLSrgVT3aQ1fZ3SCe-dEVnFJDApBYkqolP\n\nFor more videos. subscribe to AIA Malaysia's YouTube channel:\nhttps://www.youtube.com/channel/UCdTU5vd37FlTZ-xoB0xzRDA"
                  }
               }
            }
         ]
      }
      

      欲了解更多信息,请访问the API documentation page

      【讨论】:

        【解决方案6】:

        视频标题在 API 中,可以在 JavaScript 中使用点表示法访问:

        the_name_of_your_video_object.A.videoData.title
        

        【讨论】:

        • 我正在使用:video_object.getVideoData().title.
        • @cdonts 你的方法效果更好。 A.videoData 不再适合我。
        【解决方案7】:

        Robert Sim 和 cbaigorri 的回答是最好的,这就是这个时候用 JS 做的正确方法,做 GET 请求到:

        https://www.googleapis.com/youtube/v3/videos?part=snippet&amp;id={YOUTUBE_VIDEO_ID}&amp;fields=items(id,snippet)&amp;key={YOUR_API_KEY}

        关于这个的一点规范: 您可以使用逗号分隔的 youtube 视频 ID 在一个请求中获取多个视频信息。

        要获取 1 个视频,请将 {YOUTUBE_VIDEO_ID} 替换为视频 ID(例如:123456) 要在一个请求中获取更多视频,请将 {YOUTUBE_VIDEO_ID} 替换为逗号分隔的 ID(例如:123456,234567,345678,456789

        这将被视为配额中的单个请求,这样您只需 1 个配额/请求成本即可获得大量视频详细信息。

        【讨论】:

          【解决方案8】:

          而不是使用http://gdata.youtube.com/feeds/api/videos/....

          如果您已加载视频,则可以使用播放器对象的 getVideoData() 方法来检索有关视频的信息,包括标题。它将返回一个对象,其中包含:video_id、作者、标题。

          【讨论】:

            【解决方案9】:

            我的解决办法是:

            $xmlInfoVideo    = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos/".$videoId."?v=2&fields=title");
            
            foreach($xmlInfoVideo->children() as $title) { $videoTitle = strtoupper((string) $title); }
            

            这会得到视频的标题。

            【讨论】:

              【解决方案10】:

              我编写了一个函数来获取给定 id 的 Youtube 视频的标题和作者。该函数在 iframe 中加载 Youtube 视频,然后在 Youtube 发出初始消息时添加消息侦听器。该初始消息包含视频数据。然后它从页面中删除 iframe 和消息侦听器。

              import { Observable } from 'rxjs';
              
              function getVideoData$(ytId){
                  return new Observable((observer) => {
                      let embed = document.createElement('iframe');
                      embed.setAttribute('src', `https://www.youtube.com/embed/${ytId}?enablejsapi=1&widgetid=99`);
                      embed.cssText = "position: absolute; display: hidden";
                      embed.onload = function() {
                          var message = JSON.stringify({ event: 'listening', id: 99, channel: 'widget' });
                          embed.contentWindow.postMessage(message, 'https://www.youtube.com');
                      }
                      function parseData(e) {
                          const {event, id, info} = JSON.parse(e.data)
                          // console.log(JSON.parse(e.data))
                          if (event == 'initialDelivery' && id == 99) observer.next(info.videoData)
                      }
                      document.body.appendChild(embed); // load iframe
                      window.addEventListener("message", parseData) // add Api listener for initialDelivery
                      return function cleanup(){
                          window.removeEventListener("message", parseData)
                          document.body.removeChild(embed)
                      }
                  });
              }
              

              我选择返回一个 observable,因为视频必须从 yt 的服务器异步检索,然后发送回 iframe,然后发送到我们设置的消息处理程序。可以在这里使用 Promise,但我发现 Promise 会在消息侦听器被删除之前多次解析。所以我用 rxjs 只得到第一个值。以下是我如何使用此功能。

              import { firstValueFrom } from 'rxjs';
              
              getVideoDataFromUrl('https://www.youtube.com/watch?v=3vBwRfQbXkg')
              
              async function getVideoDataFromUrl (url){
                  const videoId = parseYoutubeUrl(url)
                  if (!videoId) return false
                  let videoData = await firstValueFrom(getVideoData$(videoId)) // await video data
                  console.log({videoData})
              }
              
              function parseYoutubeUrl(url) {
                  var p = /^(?:https?:\/\/)?(?:m\.|www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
                  let urlMatch = url.match(p)
                  if(urlMatch) return urlMatch[1];
                  return false;
              }
              

              【讨论】:

              • 感谢您的回答。它奏效了。
              【解决方案11】:

              使用 PHP

              <?php
              echo explode(' - YouTube',explode('</title>',explode('<title>',file_get_contents("https://www.youtube.com/watch?v=$youtube_id"))[1])[0])[0];
              ?>
              

              【讨论】:

                猜你喜欢
                • 2017-07-01
                • 2012-05-22
                • 2016-01-11
                • 2012-03-20
                • 1970-01-01
                • 2015-07-26
                • 2023-03-17
                • 2022-01-10
                相关资源
                最近更新 更多