YouTube API用于获取频道上的所有视频

问题描述 投票:143回答:14

我们需要按YouTube频道名称的视频列表(使用API​​)。

我们可以使用以下API获取频道列表(仅限频道名称):

https://gdata.youtube.com/feeds/api/channels?v=2&q=tendulkar

以下是频道的直接链接

https://www.youtube.com/channel/UCqAEtEr0A0Eo2IVcuWBfB9g

要么

WWW.YouTube.com/channel/HC-8jgBP-4rlI

现在,我们需要频道>> UCqAEtEr0A0Eo2IVcuWBfB9g或HC-8jgBP-4rlI的视频。

我们尝试了

https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&User=UC7Xayrf2k0NZiz3S04WuDNQ https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&q=UC7Xayrf2k0NZiz3S04WuDNQ

但是,它没有帮助。

我们需要在频道上发布的所有视频。上传到频道的视频可能来自多个用户,因此我认为提供用户参数不会有帮助......

youtube youtube-api
14个回答
193
投票

你需要看看YouTube Data API。您将找到有关如何访问API的文档。你也可以找到client libraries

您也可以自己提出请求。以下是从频道中检索最新视频的示例网址:

https://www.googleapis.com/youtube/v3/search?key={your_key_here}&channelId={channel_id_here}&part=snippet,id&order=date&maxResults=20

之后,您将收到带有视频ID和详细信息的JSON,您可以像这样构建视频网址:

http://www.youtube.com/watch?v={video_id_here}

3
投票

由于每个回答此问题的人都因为500视频限制而出现问题,因此这是使用Python 3中的youtube_dl的替代解决方案。此外,不需要API密钥。

  1. 安装youtube_dl:https://www.youtube.com/account_advanced
  2. sudo pip3 install youtube-dl。该ID将从UC开始。将U替换为用于上传的U(即UU ...),这是上传播放列表。
  3. 使用youtube-dl中的播放列表下载程序功能。理想情况下,您不希望下载默认播放列表中的每个视频,而只下载元数据。

示例(警告 - 需要几十分钟):

Find out your target channel's channel id

2
投票

使用不推荐使用的API版本2,上传的URL(通道UCqAEtEr0A0Eo2IVcuWBfB9g)是:

import youtube_dl, pickle # UCVTyTA7-g9nopHeHbeuvpRA is the channel id (1517+ videos) PLAYLIST_ID = 'UUVTyTA7-g9nopHeHbeuvpRA' # Late Night with Seth Meyers with youtube_dl.YoutubeDL({'ignoreerrors': True}) as ydl: playd = ydl.extract_info(PLAYLIST_ID, download=False) with open('playlist.pickle', 'wb') as f: pickle.dump(playd, f, pickle.HIGHEST_PROTOCOL) vids = [vid for vid in playd['entries'] if 'A Closer Look' in vid['title']] print(sum('Trump' in vid['title'] for vid in vids), '/', len(vids))

有一个API版本3。


1
投票

最近我不得不从一个频道中检索所有视频,并根据YouTube开发者文档:https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads

https://developers.google.com/youtube/v3/docs/playlistItems/list

哪里function playlistItemsListByPlaylistId($service, $part, $params) { $params = array_filter($params); $response = $service->playlistItems->listPlaylistItems( $part, $params ); print_r($response); } playlistItemsListByPlaylistId($service, 'snippet,contentDetails', array('maxResults' => 25, 'playlistId' => 'id of "uploads" playlist')); 是你的$service对象。

因此,您必须从频道中获取信息,以检索实际上包含频道上传的所有视频的“上传”播放列表:Google_Service_YouTube

如果使用此API,我强烈建议您将代码示例从默认代码段转换为完整示例。

因此,从频道中检索所有视频的基本代码可以是:

https://developers.google.com/youtube/v3/docs/channels/list

1
投票

Python中的示例解决方案。从这个视频中获取帮助:class YouTube { const DEV_KEY = 'YOUR_DEVELOPPER_KEY'; private $client; private $youtube; private $lastChannel; public function __construct() { $this->client = new Google_Client(); $this->client->setDeveloperKey(self::DEV_KEY); $this->youtube = new Google_Service_YouTube($this->client); $this->lastChannel = false; } public function getChannelInfoFromName($channel_name) { if ($this->lastChannel && $this->lastChannel['modelData']['items'][0]['snippet']['title'] == $channel_name) { return $this->lastChannel; } $this->lastChannel = $this->youtube->channels->listChannels('snippet, contentDetails, statistics', array( 'forUsername' => $channel_name, )); return ($this->lastChannel); } public function getVideosFromChannelName($channel_name, $max_result = 5) { $this->getChannelInfoFromName($channel_name); $params = [ 'playlistId' => $this->lastChannel['modelData']['items'][0]['contentDetails']['relatedPlaylists']['uploads'], 'maxResults'=> $max_result, ]; return ($this->youtube->playlistItems->listPlaylistItems('snippet,contentDetails', $params)); } } $yt = new YouTube(); echo '<pre>' . print_r($yt->getVideosFromChannelName('CHANNEL_NAME'), true) . '</pre>'; 像许多其他答案一样,首先要从频道ID中检索上传ID。

import urllib.request
import json

key = "YOUR_YOUTUBE_API_v3_BROWSER_KEY"

#List of channels : mention if you are pasting channel id or username - "id" or "forUsername"
ytids = [["bbcnews","forUsername"],["UCjq4pjKj9X4W9i7UnYShpVg","id"]]

newstitles = []
for ytid,ytparam in ytids:
    urld = "https://www.googleapis.com/youtube/v3/channels?part=contentDetails&"+ytparam+"="+ytid+"&key="+key
    with urllib.request.urlopen(urld) as url:
        datad = json.loads(url.read())
    uploadsdet = datad['items']
    #get upload id from channel id
    uploadid = uploadsdet[0]['contentDetails']['relatedPlaylists']['uploads']

    #retrieve list
    urld = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId="+uploadid+"&key="+key
    with urllib.request.urlopen(urld) as url:
        datad = json.loads(url.read())

    for data in datad['items']:
        ntitle =  data['snippet']['title']
        nlink = data['contentDetails']['videoId']
        newstitles.append([nlink,ntitle])

for link,title in newstitles:
    print(link, title)

-6
投票

如文档所述(video),您可以使用频道资源类型和操作列表来获取频道中的所有视频。必须使用参数'channel id'执行此操作。


86
投票

首先,您需要从用户/频道获取代表上传的播放列表的ID:

https://developers.google.com/youtube/v3/docs/channels/list#try-it

您可以使用forUsername={username} param指定用户名,或指定mine=true以获取您自己的用户名(您需要先进行身份验证)。包括part=contentDetails以查看播放列表。

GET https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=jambrose42&key={YOUR_API_KEY}

结果"relatedPlaylists"将包括"likes""uploads"播放列表。抓住"upload"的播放列表ID。另请注意,"id"是您的channelID以供将来参考。

接下来,获取该播放列表中的视频列表:

https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it

只需放入播放列表即可!

GET https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId=UUpRmvjdu3ixew5ahydZ67uA&key={YOUR_API_KEY}


55
投票

Here is来自Google Developers的视频展示了如何在YouTube API的v3中列出频道中的所有视频。

有两个步骤:

  1. 查询频道以获取“上传”ID。例如https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails
  2. 使用此“上传”ID可查询PlaylistItems以获取视频列表。例如https://www.googleapis.com/youtube/v3/playlistItems?playlistId={"uploads" Id}&key={API key}&part=snippet&maxResults=50

11
投票

获取频道列表:

通过forUserName获取频道列表:

https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forUsername=Apple&key=

按渠道ID获取频道列表:

https://www.googleapis.com/youtube/v3/channels/?part=snippet,contentDetails,statistics&id=UCE_M8A5yxnLfW0KghEeajjw&key=

获取频道部分:

https://www.googleapis.com/youtube/v3/channelSections?part=snippet,contentDetails&channelId=UCE_M8A5yxnLfW0KghEeajjw&key=

获取播放列表:

按渠道ID获取播放列表:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=

通过带有pageToken的频道ID获取播放列表:

冰淇淋和霜冻= KIDIKA

要获取PlaylistItems:

通过PlayListId获取PlaylistItems列表:

https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=

要获取视频:

按视频ID获取视频列表:

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=25&playlistId=PLHFlHpPjgk70Yv3kxQvkDEO5n5tMQia5I&key=

通过多个视频ID获取视频列表:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw&key=

获取评论列表

通过视频ID获取评论列表:

https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw,Qgy6LaO3SB0,7yPJXGO2Dcw&key= **** kQak&键= A **********ķ

按渠道ID获取评论列表:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=el ***** Q&键= AI ********ķ

获得评论列表allThreadsRelatedToChannelId:

https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&channelId=U ***** ntcQ&键= AI *****ķ

这里所有api都是Get方法。

根据频道ID,我们无法直接获取所有视频,这是重要的一点。

对于整合https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=UC


7
投票

下面是一个Python替代品,不需要任何特殊包。通过提供频道ID,它返回该频道的视频链接列表。请注意,您需要一个https://developers.google.com/youtube/v3/quickstart/ios?ver=swift才能工作。

API Key

7
投票

尝试使用以下内容。它可能会帮助你。

import urllib import json def get_all_video_in_channel(channel_id): api_key = YOUR API KEY base_video_url = 'https://www.youtube.com/watch?v=' base_search_url = 'https://www.googleapis.com/youtube/v3/search?' first_url = base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key, channel_id) video_links = [] url = first_url while True: inp = urllib.urlopen(url) resp = json.load(inp) for i in resp['items']: if i['id']['kind'] == "youtube#video": video_links.append(base_video_url + i['id']['videoId']) try: next_page_token = resp['nextPageToken'] url = first_url + '&pageToken={}'.format(next_page_token) except: break return video_links

在此作者,您可以指定频道名称和“q”,因为您可以提供搜索关键字。


6
投票

只需三个步骤:

  1. 订阅:列表 - > https://gdata.youtube.com/feeds/api/videos?author=cnn&v=2&orderby=updated&alt=jsonc&q=news {oauth_token}
  2. 频道:列表 - > https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&maxResults=50&mine=true&access_token= {channel_id}&key = {YOUR_API_KEY}
  3. PlaylistItems:list - > https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id= {playlist_id}&key = {YOUR_API_KEY}

5
投票

感谢此处和其他地方分享的参考资料,我制作了一个在线脚本/工具,可用于获取频道的所有视频。

它结合了对https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=youtube.channels.listplaylistItems的API调用。它使用递归函数使得异步回调在获得有效响应时运行下一次迭代。

这也可以限制一次发出的实际请求数量,从而确保您不会违反YouTube API规则。共享缩短的片段,然后链接到完整的代码。通过使用响应中的nextPageToken值来获取接下来的50个结果,我得到了每个呼叫限制的50个最大结果,依此类推。

videos

这有一个基本的视频列表,包括身份,标题,出版日期和类似。但是为了获得每个视频的更多细节,例如视图计数和喜欢,必须对function getVideos(nextPageToken, vidsDone, params) { $.getJSON("https://www.googleapis.com/youtube/v3/playlistItems", { key: params.accessKey, part: "snippet", maxResults: 50, playlistId: params.playlistId, fields: "items(snippet(publishedAt, resourceId/videoId, title)), nextPageToken", pageToken: ( nextPageToken || '') }, function(data) { // commands to process JSON variable, extract the 50 videos info if ( vidsDone < params.vidslimit) { // Recursive: the function is calling itself if // all videos haven't been loaded yet getVideos( data.nextPageToken, vidsDone, params); } else { // Closing actions to do once we have listed the videos needed. } }); } 进行API调用。

videos

参见// Looping through an array of video id's function fetchViddetails(i) { $.getJSON("https://www.googleapis.com/youtube/v3/videos", { key: document.getElementById("accesskey").value, part: "snippet,statistics", id: vidsList[i] }, function(data) { // Commands to process JSON variable, extract the video // information and push it to a global array if (i < vidsList.length - 1) { fetchViddetails(i+1) // Recursive: calls itself if the // list isn't over. } }); full code here。 (编辑:修复github链接) 编辑:依赖关系:JQuery,Papa.parse


3
投票

以下代码将返回您频道下的所有视频ID

live version here

注意:登录后,您可以在<?php $baseUrl = 'https://www.googleapis.com/youtube/v3/'; // https://developers.google.com/youtube/v3/getting-started $apiKey = 'API_KEY'; // If you don't know the channel ID see below $channelId = 'CHANNEL_ID'; $params = [ 'id'=> $channelId, 'part'=> 'contentDetails', 'key'=> $apiKey ]; $url = $baseUrl . 'channels?' . http_build_query($params); $json = json_decode(file_get_contents($url), true); $playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads']; $params = [ 'part'=> 'snippet', 'playlistId' => $playlist, 'maxResults'=> '50', 'key'=> $apiKey ]; $url = $baseUrl . 'playlistItems?' . http_build_query($params); $json = json_decode(file_get_contents($url), true); $videos = []; foreach($json['items'] as $video) $videos[] = $video['snippet']['resourceId']['videoId']; while(isset($json['nextPageToken'])){ $nextUrl = $url . '&pageToken=' . $json['nextPageToken']; $json = json_decode(file_get_contents($nextUrl), true); foreach($json['items'] as $video) $videos[] = $video['snippet']['resourceId']['videoId']; } print_r($videos); 获取频道ID。

© www.soinside.com 2019 - 2024. All rights reserved.