首页 > 解决方案 > 从 YouTube 获取直播的更好方法?

问题描述

据我所知,获取 youtube 频道的直播视频 ID 的唯一方法是https://www.googleapis.com/youtube/v3/search使用频道 ID 查询端点。这将返回该频道的直播流列表。在我的网站上,我每 5 分钟自动执行一次,以便它可以在我上线时自动检查和宣布。

这样做的问题是,每个搜索事务的查询成本为 100。因此,每 5 分钟扫描一个频道,每天会花费 28,800 个查询。我的网站每天只有 30,000 个配额限制。这意味着我无法在抓取中添加第二个频道;因为这会使查询成本增加一倍。

search除了端点之外,还有更好的方法来获取频道的流视频 ID吗?

标签: youtube-api

解决方案


使用@Marco 链接的想​​法,我想出了一个更好的解决方案。

抓取频道的主页并获取它的 html 内容。我把它们放在变量中$html。然后我获取这些内容并通过以下方式运行它:

if (preg_match('#window\["ytInitialData"\]\s?=\s?(.+?);#i', $html, $matches))
{
    // this gets the YT's JSON for the channel

    $json = json_decode($matches[1], true);
    $json = $json['contents']['twoColumnBrowseResultsRenderer']['tabs'][0]['tabRenderer']['content'];
    $json = $json['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0];
    if (empty($json['channelFeaturedContentRenderer'])) { return; }
    
    // if there is no 'channelFeaturedContentRenderer' section, there are no live streams
    
    foreach ($json['channelFeaturedContentRenderer']['items'] AS $item)
    {
        if (empty($item['videoRenderer']['badges'])) { continue; }
        
        // if the video has no badges, its not a live stream.
    
        $stream = $item['videoRenderer'];
        
        // all the stream's details are available here
    }
}

很容易。它还支持获取通道上的所有流;如果一个频道一次有多个流。


推荐阅读