YouTube Data API获取最新视频异常问题求助
问题分析与解决方案
核心问题:URL参数转义错误
你的代码中API请求URL使用了HTML实体&分隔参数,但在JavaScript字符串中不需要这种转义——这会导致API错误解析参数(比如&channelId会被识别为无效参数amp;channelId),进而返回非预期的旧视频数据。
修复步骤
1. 修正API请求URL
将URL中所有&替换为&,恢复正确的参数分隔逻辑:
async function getLastVideo() { // 修正参数分隔符为&,移除不必要的HTML实体转义 const url = `https://www.googleapis.com/youtube/v3/search?key=${apiKey}&channelId=${channelId}&order=date&part=snippet&type=video&maxResults=1`; try { const response = await fetch(url); const data = await response.json(); if (data.items.length > 0) { const lastVideoId = data.items[0].id.videoId; const lastVideoUrl = `https://www.youtube.com/watch?v=${lastVideoId}`; document.getElementById('youtube-last-video-1').href = lastVideoUrl; document.getElementById('youtube-last-video-2').href = lastVideoUrl; document.getElementById('youtube-last-video-3').href = lastVideoUrl; } else { console.error('No se encontraron videos.'); } } catch (error) { console.error('Error al obtener el último video:', error); } } window.onload = getLastVideo;
2. 更可靠的替代方案:使用频道上传播放列表
search接口可能存在索引延迟,建议直接调用频道官方上传播放列表接口,确保获取到最新的公开视频:
async function getLastVideo() { try { // 第一步:获取频道的上传播放列表ID const channelResponse = await fetch(`https://www.googleapis.com/youtube/v3/channels?key=${apiKey}&id=${channelId}&part=contentDetails`); const channelData = await channelResponse.json(); if (!channelData.items[0]) { console.error('频道不存在或无权限访问'); return; } const uploadsPlaylistId = channelData.items[0].contentDetails.relatedPlaylists.uploads; // 第二步:从上传列表获取最新视频 const playlistResponse = await fetch(`https://www.googleapis.com/youtube/v3/playlistItems?key=${apiKey}&playlistId=${uploadsPlaylistId}&order=date&part=snippet&maxResults=1`); const playlistData = await playlistResponse.json(); if (playlistData.items.length > 0) { const lastVideoId = playlistData.items[0].snippet.resourceId.videoId; const lastVideoUrl = `https://www.youtube.com/watch?v=${lastVideoId}`; document.getElementById('youtube-last-video-1').href = lastVideoUrl; document.getElementById('youtube-last-video-2').href = lastVideoUrl; document.getElementById('youtube-last-video-3').href = lastVideoUrl; } else { console.error('No se encontraron videos.'); } } catch (error) { console.error('Error al obtener el último video:', error); } } window.onload = getLastVideo;
额外排查点
- 确认频道最新视频为公开状态,私密/未列出视频无法通过API获取
- 检查API密钥配额是否充足,配额耗尽可能返回缓存的旧数据
- 验证
channelId是否正确,避免因ID错误获取到其他频道内容
内容的提问来源于stack exchange,提问作者Lucas Olivares
相关产品推荐
相关产品推荐

