我正在尝试使用 youtube 的 api 使用 node.js 通过频道名称获取频道的订阅者数量。我该怎么做?
您可以使用 官方 YouTube API channels.list 方法来获取统计信息,例如:subscriberCount、videoCount 和 viewCount。
从 YouTube 频道获取统计数据 | 在 Fusebit 中运行 |
---|
const youtube = googleClient.youtube('v3');
const channelName = 'GoogleDevelopers';
const channelsResponse = await youtube.channels.list({
part: 'id,statistics',
forUsername: channelName,
});
if (channelsResponse.data.items && channelsResponse.data.items.length) {
const { statistics: { subscriberCount, videoCount, viewCount } } = channelsResponse.data.items[0];
console.log(`The channel ${channelName} has 🧑🏾🤝🧑🏾 ${subscriberCount} subscribers, 🎬 ${videoCount} videos and 👀 ${viewCount} views.`);
} else {
console.log = `Channel not found: ${channelName}`;
}
[更新]
根据评论,这里是一个如何根据搜索词搜索频道的示例,然后您将使用频道 id 来获取统计信息,从前面的代码,而不是发送您将发送的 forUserName 参数id 请参阅此处的搜索 API 文档
const channelsResponse = await youtube.search.list({
part: 'snippet',
q: searchTerm,
maxResults: 10,
type: 'channel',
order: 'viewCount' // show more popular first
});
这是搜索中每个项目返回的 响应对象
{
"kind": "youtube#searchResult",
"etag": etag,
"id": {
"kind": string,
"videoId": string,
"channelId": string,
"playlistId": string
},
"snippet": {
"publishedAt": datetime,
"channelId": string,
"title": string,
"description": string,
"thumbnails": {
(key): {
"url": string,
"width": unsigned integer,
"height": unsigned integer
}
},
"channelTitle": string,
"liveBroadcastContent": string
}
}
请求:
https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UC1gi4ynIYAcd_BmFlJsLOWg&key=your_api_key
回复格式:
{
"kind": "youtube#channelListResponse",
"etag": "vdXkdxBKA5DKypndZTEWUM_tBPQ",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "R5sb6hhxom_vkPLE9izol0WBeVg",
"id": "UC1gi4ynIYAcd_BmFlJsLOWg",
"statistics": {
"viewCount": "35960",
"subscriberCount": "242",
"hiddenSubscriberCount": false,
"videoCount": "26"
}
}
]
}