如何从YouTube播放列表获取视频标题与描述(已获取缩略图)
嘿,你已经离成功只差一步啦!你请求API的时候已经指定了part: 'contentDetails,snippet',而标题和描述刚好就藏在snippet字段里,根本不用额外改请求参数,只需要在回调里把这些数据提取出来就行~
先给你调整一下代码,让它能同时展示缩略图、标题和描述:
修改后的HTML
我们可以把列表的ID改得更贴合用途,每个列表项里会包含完整的视频信息:
<ul id="videoList"></ul>
修改后的Script.js
注意要把key参数补全(你得用自己的YouTube Data API密钥哦),然后在回调里解析snippet里的字段:
var maxVideos = 5; $(document).ready(function(){ $.get( "https://www.googleapis.com/youtube/v3/playlistItems",{ part: 'contentDetails,snippet', playlistId:'PLJYHm_ZxWCKnQmapkDs7x47jkr-nw3l50', maxResults: maxVideos, key: '你的API密钥' // 记得替换成你自己的有效API密钥 }, function(data){ var videoList = $('#videoList'); // 遍历返回的每一个播放列表项 $.each(data.items, function(index, item){ // 从snippet中提取所需信息 const thumbnail = item.snippet.thumbnails.medium.url; // 这里用medium尺寸,你也可以换成default/high const title = item.snippet.title; const description = item.snippet.description; // 构建单个视频的HTML结构 const listItem = ` <li style="margin-bottom: 20px; list-style: none;"> <img src="${thumbnail}" alt="${title}" style="width: 320px; height: auto;"> <h3 style="margin: 10px 0;">${title}</h3> <p style="color: #666; margin: 0;">${description.length > 150 ? description.substring(0, 150) + '...' : description}</p> </li> `; // 添加到列表中 videoList.append(listItem); }); }); });
几个关键说明:
- API密钥:YouTube Data API必须要有有效的密钥才能请求,如果你还没有,得去Google Cloud控制台创建一个并启用YouTube Data API v3。
- 字段位置:标题是
item.snippet.title,描述是item.snippet.description,缩略图在item.snippet.thumbnails下有多个尺寸可选,根据你的需求选就行。 - 描述截取:我加了个小判断,如果描述太长就截取前150个字符加省略号,避免页面内容太冗余,你可以根据自己的需求调整长度。
这样修改后,就能同时展示缩略图、标题和描述啦!
内容的提问来源于stack exchange,提问作者Obaid
相关产品推荐
相关产品推荐

