首页 文章

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

提问于
浏览
130

我们需要按YouTube Channels 名称的视频列表(使用API) .

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

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

以下是 Channels 的直接链接

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

要么

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

现在,我们需要 Channels >> 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

但是,它没有帮助 .

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

12 回答

  • 2

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

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

    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}
    
  • 78

    首先,您需要从用户/ Channels 获取代表上传的播放列表的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" 播放列表 . grab "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}

  • 3

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

    有两个步骤:

    • 查询 Channels 以获取"uploads" Id . 例如 https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails

    • 使用此"uploads" Id查询PlaylistItems以获取视频列表 . 例如 https://www.googleapis.com/youtube/v3/playlistItems?playlistId={"uploads" Id}&key={API key}&part=snippet&maxResults=50

  • 7

    下面是一个Python替代品,不需要任何特殊包 . 通过提供 Channels ID,它返回该 Channels 的视频链接列表 . 请注意,您需要API Key才能使用它 .

    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
    
  • 170

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

    https://gdata.youtube.com/feeds/api/videos?author=cnn&v=2&orderby=updated&alt=jsonc&q=news

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

  • 7

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

    它将API调用与 youtube.channels.listplaylistItemsvideos 相结合 . 它使用递归函数使得异步回调在获得有效响应时运行下一次迭代 .

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

    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.
                 }
        });
    }
    

    这有一个基本的视频列表,包括身份, Headers ,出版日期和类似 . 但是为了获得每个视频的更多细节,例如视图计数和喜欢,必须对 videos 进行API调用 .

    // 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 herelive version here . (编辑:修复github链接)

  • 4

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

    <?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);
    

    注意:登录后,您可以通过https://www.youtube.com/account_advanced获取 Channels ID .

  • 2

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

    https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads

    有一个API版本3 .

  • 1

    因为回答这个问题的每个人都有问题,因为 500 video limit 这是在 Python 3 中使用 youtube_dl 的替代解决方案 . 另外, no API key is needed .

    • 安装youtube_dl: sudo pip3 install youtube-dl

    • Find out your target channel's channel id . 该ID将从UC开始 . 用U代替通道的C代表(即UU ...),这是 upload playlist .

    • 使用youtube-dl中的 playlist downloader feature . 理想情况下,您不希望下载默认播放列表中的每个视频,而只下载元数据 .

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

    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))
    
  • 0

    最近我不得不从一个 Channels 中检索所有视频,并根据YouTube开发者文档: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 对象 .

    因此,您必须从 Channels 中获取信息,以检索实际包含 Channels 上传的所有视频的"uploads"播放列表:https://developers.google.com/youtube/v3/docs/channels/list

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

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

    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>';
    
  • -4

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

相关问题