如何检查 YouTube 频道是否正在直播
How to check if YouTube channel is streaming live
我找不到任何信息来检查 YouTube 频道是否真的在流式传输。
使用 Twitch,您只需要频道名称,使用 API,您可以检查是否有直播。
我不想使用 OAuth,通常 public API 密钥就足够了。就像查看某个频道的视频一样,我想知道该频道是否正在播放。
您可以使用 search.list
并指定频道 ID,将类型设置为 video
,并将 eventType
设置为 live
。
例如,当我搜索:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCXswCcAMb5bvEUIDEzXFGYg&type=video&eventType=live&key=[API_KEY]
我得到以下信息:
{
"kind": "youtube#searchListResponse",
"etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/gE5P_aKHWIIc6YSpRcOE57lf9oE\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/H-6Tm7-JewZC0-CW4ALwOiq9wjs\"",
"id": {
"kind": "youtube#video",
"videoId": "W4HL6h-ZSws"
},
"snippet": {
"publishedAt": "2015-09-08T11:46:23.000Z",
"channelId": "UCXswCcAMb5bvEUIDEzXFGYg",
"title": "Borussia Dortmund vs St. Pauli 1-0 Live Stream",
"description": "Borussia Dortmund vs St. Pauli Live Stream Friendly Match.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/hqdefault.jpg"
}
},
"channelTitle": "",
"liveBroadcastContent": "live"
}
}
]
}
我知道这是旧的,但我自己用 PHP 弄明白了。
$API_KEY = 'your api3 key';
$ChannelID = 'the users channel id';
$channelInfo = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='.$ChannelID.'&type=video&eventType=live&key='.$API_KEY;
$extractInfo = file_get_contents($channelInfo);
$extractInfo = str_replace('},]',"}]",$extractInfo);
$showInfo = json_decode($extractInfo, true);
if($showInfo['pageInfo']['totalResults'] === 0){
echo 'Users channel is Offline';
} else {
echo 'Users channel is LIVE!';
}
您默认拥有的 10,000 个中的搜索方法 (https://www.googleapis.com/youtube/v3/search) is awfully expensive to use though. It costs 100 quota units (https://developers.google.com/youtube/v3/determine_quota_cost)。
这意味着您每天只能收到 100 个请求,这太糟糕了。
您可以请求增加配额,但这似乎是强行解决问题。
真的没有其他更简单的方法吗?
如果你将 streamlink 指向 https://www.youtube.com/channel/CHANNEL_ID/live
link,它会告诉你它是否在线
- 例如lofi beats平时直播,
$ streamlink "https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow/live"
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow/live
Available streams: 144p (worst), 240p, 360p, 480p, 720p, 1080p (best)
- 而 MKBHD 不是
$ streamlink "https://www.youtube.com/c/mkbhd/live"
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/c/mkbhd/live
error: Could not find a video on this page
我发现 youtube API 考虑到搜索操作的成本非常严格。使用 aiohttp 和 beautifulsoup 进行网络抓取不是一种选择,因为更好的指标需要 javascript 支持。因此我转向 selenium。我寻找 css 选择器
#info-text
然后搜索字符串 Started streaming
或其中包含 watching now
。
您也可以 运行 在 heroku 上使用 一个小的 API。
我也在为 API 的限制而苦苦挣扎。我发现的最可靠和最便宜的方法就是向 https://www.youtube.com/channel/CHANNEL_ID/live
发送 HEAD
请求。如果频道是实时的,那么它将自动加载流。如果没有,那么它将加载频道视频提要。您可以简单地检查 Content-Length
header 大小来确定哪个。如果直播,大小几乎是不直播时的 2 倍。
并且根据您所在的地区,您可能需要接受 cookie 同意页面。只需使用 cookies={ "CONSENT": "YES+cb.20210420-15-p1.en-GB+FX+634" }
.
发送您的请求
伙计们,我找到了更好的方法来做到这一点。是的,它要求您向 YouTube 页面发出 GET 请求并解析 HTML、,但是 它可以与较新的版本一起使用 + 在征得同意的情况下使用 + 与验证码一起使用(很可能, 90%)
您需要做的就是向 https://youtube.com/channel/[CHANNELID]/live
发出请求并检查 <link rel="canonical" />
标签的 href
属性。
例如,
<link rel="canonical" href="https://www.youtube.com/channel/UC4cueEAH9Oq94E1ynBiVJhw">
表示没有直播,而
<link rel="canonical" href="https://www.youtube.com/watch?v=SR9w_ofpqkU">
表示有流,你甚至可以通过videoid
获取它的数据。
由于规范 URL 对于 SEO 非常重要并且重定向在 GET
或 HEAD
请求中不再起作用,我建议使用我的方法。
这里还有我使用的简单脚本:
import { parse } from 'node-html-parser'
import fetch from 'node-fetch'
const channelID = process.argv[2] // process.argv is array of arguments passed in console
const response = await fetch(`https://youtube.com/channel/${channelID}/live`)
const text = await response.text()
const html = parse(text)
const canonicalURLTag = html.querySelector('link[rel=canonical]')
const canonicalURL = canonicalURLTag.getAttribute('href')
const isStreaming = canonicalURL.includes('/watch?v=')
console.log(isStreaming)
然后运行 npm init -y && npm i node-html-parser node-fetch
在工作目录中创建项目并安装依赖项
然后 运行 node isStreaming.js UC4cueEAH9Oq94E1ynBiVJhw
它将打印 true/false (每次执行 400-600 毫秒)
它确实需要您依赖 node-html-parser
和 node-fetch
,但您可以使用内置 HTTP 库(很糟糕)发出请求并重写它以使用正则表达式。 (不要用正则表达式解析 HTML。)
我发现最简单的方法是抓取网站。这可以通过找到这个来完成:
<link rel="canonical" href="linkToActualYTLiveVideoPage">
如 .
这是我的简单 Python 代码,使用 bs4
:
import requests
from bs4 import BeautifulSoup
def is_liveYT():
channel_url = "https://www.youtube.com/c/LofiGirl/live"
page = requests.get(channel_url, cookies={'CONSENT': 'YES+42'})
soup = BeautifulSoup(page.content, "html.parser")
live = soup.find("link", {"rel": "canonical"})
if live:
print("Streaming")
else:
print("Not Streaming")
if __name__ == "__main__":
is_liveYT()
老实说,YouTube 没有通过 API 执行此操作的简单方法,尽管这可能更容易。
每个 YouTube 频道都作为永久直播,即使该频道目前没有进行直播。在 liveStream
resource 中,您可以找到一个名为 isDefaultStream
.
的布尔值
但是我们在哪里可以得到这个视频(直播)id?转到 https://www.youtube.com/user/CHANNEL_ID/live
,右键单击流并复制视频 URL。
您现在可以向
https://youtube.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id=[VIDEO_ID]&key=[API_KEY]
(此请求的 配额成本 为 1 个单位,请参阅 here)
如果流当前为 active/online,这将是结果。
{
"kind": "",
"etag": "",
"items": [
{
"kind": "",
"etag": "",
"id": "",
"liveStreamingDetails": {
"actualStartTime": "",
"scheduledStartTime": "",
"concurrentViewers": "",
"activeLiveChatId": ""
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
如果流当前处于离线状态,则 属性 concurrentViewers
将不存在。换句话说,线上直播和线下直播的唯一区别就是concurrentViewers
存在与否。有了这些信息,您可以检查频道当前是否正在流式传输(至少对于他的默认流)。
我发现 非常有用,但它不区分有直播的频道 已安排 和正在直播的频道 [=19] =]直播.
为了区分预定和直播,我扩展了他的代码以访问 YouTube 数据 API 以查找直播详细信息:
import { parse } from 'node-html-parser'
import fetch from 'node-fetch'
const youtubeAPIkey = 'YOUR_YOUTUBE_API_KEY'
const youtubeURLbase = 'https://www.googleapis.com/youtube/v3/videos?key=' + youtubeAPIkey + '&part=liveStreamingDetails,snippet&id='
const c = {cid: process.argv[2]} // process.argv is array of arguments passed in console
const response = await fetch(`https://youtube.com/channel/${c.cid}/live`)
const text = await response.text()
const html = parse(text)
const canonicalURLTag = html.querySelector('link[rel=canonical]')
const canonicalURL = canonicalURLTag.getAttribute('href')
c.live = false
c.configured = canonicalURL.includes('/watch?v=')
if (!c.configured) process.exit()
c.vid = canonicalURL.match(/(?<==).*/)[0]
const data = await fetch(youtubeURLbase + c.vid).then(response => response.json())
if (data.error) {
console.error(data)
process.exit(1)
}
const i = data.items.pop() // pop() grabs the last item
c.title = i.snippet.title
c.thumbnail = i.snippet.thumbnails.standard.url
c.scheduledStartTime = i.liveStreamingDetails.scheduledStartTime
c.live = i.liveStreamingDetails.hasOwnProperty('actualStartTime')
if (c.live) {
c.actualStartTime = i.liveStreamingDetails.actualStartTime
}
console.log(c)
上面的示例输出:
% node index.js UCNlfGuzOAKM1sycPuM_QTHg
{
cid: 'UCNlfGuzOAKM1sycPuM_QTHg',
live: true,
configured: true,
vid: '8yRgYiNH39E',
title: ' Deep Focus 24/7 - Ambient Music For Studying, Concentration, Work And Meditation',
thumbnail: 'https://i.ytimg.com/vi/8yRgYiNH39E/sddefault_live.jpg',
scheduledStartTime: '2022-05-23T01:25:00Z',
actualStartTime: '2022-05-23T01:30:22Z'
}
我找不到任何信息来检查 YouTube 频道是否真的在流式传输。 使用 Twitch,您只需要频道名称,使用 API,您可以检查是否有直播。
我不想使用 OAuth,通常 public API 密钥就足够了。就像查看某个频道的视频一样,我想知道该频道是否正在播放。
您可以使用 search.list
并指定频道 ID,将类型设置为 video
,并将 eventType
设置为 live
。
例如,当我搜索:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCXswCcAMb5bvEUIDEzXFGYg&type=video&eventType=live&key=[API_KEY]
我得到以下信息:
{
"kind": "youtube#searchListResponse",
"etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/gE5P_aKHWIIc6YSpRcOE57lf9oE\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"sGDdEsjSJ_SnACpEvVQ6MtTzkrI/H-6Tm7-JewZC0-CW4ALwOiq9wjs\"",
"id": {
"kind": "youtube#video",
"videoId": "W4HL6h-ZSws"
},
"snippet": {
"publishedAt": "2015-09-08T11:46:23.000Z",
"channelId": "UCXswCcAMb5bvEUIDEzXFGYg",
"title": "Borussia Dortmund vs St. Pauli 1-0 Live Stream",
"description": "Borussia Dortmund vs St. Pauli Live Stream Friendly Match.",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/W4HL6h-ZSws/hqdefault.jpg"
}
},
"channelTitle": "",
"liveBroadcastContent": "live"
}
}
]
}
我知道这是旧的,但我自己用 PHP 弄明白了。
$API_KEY = 'your api3 key';
$ChannelID = 'the users channel id';
$channelInfo = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='.$ChannelID.'&type=video&eventType=live&key='.$API_KEY;
$extractInfo = file_get_contents($channelInfo);
$extractInfo = str_replace('},]',"}]",$extractInfo);
$showInfo = json_decode($extractInfo, true);
if($showInfo['pageInfo']['totalResults'] === 0){
echo 'Users channel is Offline';
} else {
echo 'Users channel is LIVE!';
}
您默认拥有的 10,000 个中的搜索方法 (https://www.googleapis.com/youtube/v3/search) is awfully expensive to use though. It costs 100 quota units (https://developers.google.com/youtube/v3/determine_quota_cost)。 这意味着您每天只能收到 100 个请求,这太糟糕了。
您可以请求增加配额,但这似乎是强行解决问题。
真的没有其他更简单的方法吗?
如果你将 streamlink 指向 https://www.youtube.com/channel/CHANNEL_ID/live
link,它会告诉你它是否在线
- 例如lofi beats平时直播,
$ streamlink "https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow/live"
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/channel/UCSJ4gkVC6NrvII8umztf0Ow/live
Available streams: 144p (worst), 240p, 360p, 480p, 720p, 1080p (best)
- 而 MKBHD 不是
$ streamlink "https://www.youtube.com/c/mkbhd/live"
[cli][info] Found matching plugin youtube for URL https://www.youtube.com/c/mkbhd/live
error: Could not find a video on this page
我发现 youtube API 考虑到搜索操作的成本非常严格。使用 aiohttp 和 beautifulsoup 进行网络抓取不是一种选择,因为更好的指标需要 javascript 支持。因此我转向 selenium。我寻找 css 选择器
#info-text
然后搜索字符串 Started streaming
或其中包含 watching now
。
您也可以 运行 在 heroku 上使用
我也在为 API 的限制而苦苦挣扎。我发现的最可靠和最便宜的方法就是向 https://www.youtube.com/channel/CHANNEL_ID/live
发送 HEAD
请求。如果频道是实时的,那么它将自动加载流。如果没有,那么它将加载频道视频提要。您可以简单地检查 Content-Length
header 大小来确定哪个。如果直播,大小几乎是不直播时的 2 倍。
并且根据您所在的地区,您可能需要接受 cookie 同意页面。只需使用 cookies={ "CONSENT": "YES+cb.20210420-15-p1.en-GB+FX+634" }
.
伙计们,我找到了更好的方法来做到这一点。是的,它要求您向 YouTube 页面发出 GET 请求并解析 HTML、,但是 它可以与较新的版本一起使用 + 在征得同意的情况下使用 + 与验证码一起使用(很可能, 90%)
您需要做的就是向 https://youtube.com/channel/[CHANNELID]/live
发出请求并检查 <link rel="canonical" />
标签的 href
属性。
例如,
<link rel="canonical" href="https://www.youtube.com/channel/UC4cueEAH9Oq94E1ynBiVJhw">
表示没有直播,而
<link rel="canonical" href="https://www.youtube.com/watch?v=SR9w_ofpqkU">
表示有流,你甚至可以通过videoid
获取它的数据。
由于规范 URL 对于 SEO 非常重要并且重定向在 GET
或 HEAD
请求中不再起作用,我建议使用我的方法。
这里还有我使用的简单脚本:
import { parse } from 'node-html-parser'
import fetch from 'node-fetch'
const channelID = process.argv[2] // process.argv is array of arguments passed in console
const response = await fetch(`https://youtube.com/channel/${channelID}/live`)
const text = await response.text()
const html = parse(text)
const canonicalURLTag = html.querySelector('link[rel=canonical]')
const canonicalURL = canonicalURLTag.getAttribute('href')
const isStreaming = canonicalURL.includes('/watch?v=')
console.log(isStreaming)
然后运行 npm init -y && npm i node-html-parser node-fetch
在工作目录中创建项目并安装依赖项
然后 运行 node isStreaming.js UC4cueEAH9Oq94E1ynBiVJhw
它将打印 true/false (每次执行 400-600 毫秒)
它确实需要您依赖 node-html-parser
和 node-fetch
,但您可以使用内置 HTTP 库(很糟糕)发出请求并重写它以使用正则表达式。 (不要用正则表达式解析 HTML。)
我发现最简单的方法是抓取网站。这可以通过找到这个来完成:
<link rel="canonical" href="linkToActualYTLiveVideoPage">
如
这是我的简单 Python 代码,使用 bs4
:
import requests
from bs4 import BeautifulSoup
def is_liveYT():
channel_url = "https://www.youtube.com/c/LofiGirl/live"
page = requests.get(channel_url, cookies={'CONSENT': 'YES+42'})
soup = BeautifulSoup(page.content, "html.parser")
live = soup.find("link", {"rel": "canonical"})
if live:
print("Streaming")
else:
print("Not Streaming")
if __name__ == "__main__":
is_liveYT()
老实说,YouTube 没有通过 API 执行此操作的简单方法,尽管这可能更容易。
每个 YouTube 频道都作为永久直播,即使该频道目前没有进行直播。在 liveStream
resource 中,您可以找到一个名为 isDefaultStream
.
但是我们在哪里可以得到这个视频(直播)id?转到 https://www.youtube.com/user/CHANNEL_ID/live
,右键单击流并复制视频 URL。
您现在可以向
https://youtube.googleapis.com/youtube/v3/videos?part=liveStreamingDetails&id=[VIDEO_ID]&key=[API_KEY]
(此请求的 配额成本 为 1 个单位,请参阅 here)
如果流当前为 active/online,这将是结果。
{
"kind": "",
"etag": "",
"items": [
{
"kind": "",
"etag": "",
"id": "",
"liveStreamingDetails": {
"actualStartTime": "",
"scheduledStartTime": "",
"concurrentViewers": "",
"activeLiveChatId": ""
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
如果流当前处于离线状态,则 属性 concurrentViewers
将不存在。换句话说,线上直播和线下直播的唯一区别就是concurrentViewers
存在与否。有了这些信息,您可以检查频道当前是否正在流式传输(至少对于他的默认流)。
我发现
为了区分预定和直播,我扩展了他的代码以访问 YouTube 数据 API 以查找直播详细信息:
import { parse } from 'node-html-parser'
import fetch from 'node-fetch'
const youtubeAPIkey = 'YOUR_YOUTUBE_API_KEY'
const youtubeURLbase = 'https://www.googleapis.com/youtube/v3/videos?key=' + youtubeAPIkey + '&part=liveStreamingDetails,snippet&id='
const c = {cid: process.argv[2]} // process.argv is array of arguments passed in console
const response = await fetch(`https://youtube.com/channel/${c.cid}/live`)
const text = await response.text()
const html = parse(text)
const canonicalURLTag = html.querySelector('link[rel=canonical]')
const canonicalURL = canonicalURLTag.getAttribute('href')
c.live = false
c.configured = canonicalURL.includes('/watch?v=')
if (!c.configured) process.exit()
c.vid = canonicalURL.match(/(?<==).*/)[0]
const data = await fetch(youtubeURLbase + c.vid).then(response => response.json())
if (data.error) {
console.error(data)
process.exit(1)
}
const i = data.items.pop() // pop() grabs the last item
c.title = i.snippet.title
c.thumbnail = i.snippet.thumbnails.standard.url
c.scheduledStartTime = i.liveStreamingDetails.scheduledStartTime
c.live = i.liveStreamingDetails.hasOwnProperty('actualStartTime')
if (c.live) {
c.actualStartTime = i.liveStreamingDetails.actualStartTime
}
console.log(c)
上面的示例输出:
% node index.js UCNlfGuzOAKM1sycPuM_QTHg
{
cid: 'UCNlfGuzOAKM1sycPuM_QTHg',
live: true,
configured: true,
vid: '8yRgYiNH39E',
title: ' Deep Focus 24/7 - Ambient Music For Studying, Concentration, Work And Meditation',
thumbnail: 'https://i.ytimg.com/vi/8yRgYiNH39E/sddefault_live.jpg',
scheduledStartTime: '2022-05-23T01:25:00Z',
actualStartTime: '2022-05-23T01:30:22Z'
}