Javascript 如何使用 YouTube API 获取视频观看次数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3331176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:12:03  来源:igfitidea点击:

How to get number of video views with YouTube API?

javascriptyoutube-api

提问by Ante

The question is very simple. How to get number of video views with YouTube API?

问题很简单。如何使用 YouTube API 获取视频观看次数?

enter image description here

在此处输入图片说明

The task is simple but I would like to use that query on large number of videos very often. Is there any way to call their Youtube API and get it? (something like facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com)

任务很简单,但我想经常在大量视频上使用该查询。有没有办法调用他们的 Youtube API 并获取它?(类似于 facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com

采纳答案by Victor

I think, the easiest way, is to get video info in JSON format. If you want to use JavaScript, try jQuery.getJSON()... But I prefer PHP:

我认为,最简单的方法是获取 JSON 格式的视频信息。如果你想使用 JavaScript,试试 jQuery.getJSON()... 但我更喜欢 PHP:

<?php
$video_ID = 'your-video-ID';
$JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&alt=json");
$JSON_Data = json_decode($JSON);
$views = $JSON_Data->{'entry'}->{'yt$statistics'}->{'viewCount'};
echo $views;
?>

Ref: Youtube API - Retrieving information about a single video

参考:Youtube API - 检索有关单个视频的信息

回答by Matias Molinas

You can use the new YouTube Data API v3

您可以使用新的 YouTube 数据 API v3

if you retrieve the video, the statisticspart contains the viewCount:

如果您检索视频,则统计部分包含viewCount

from the doc:

从文档:

https://developers.google.com/youtube/v3/docs/videos#resource

https://developers.google.com/youtube/v3/docs/videos#resource

statistics.viewCount / The number of times the video has been viewed.

statistics.viewCount / 视频被查看的次数。

You can retrieve this info in the client side, or in the server side using some of the client libraries:

您可以在客户端或服务器端使用一些客户端库检索此信息:

https://developers.google.com/youtube/v3/libraries

https://developers.google.com/youtube/v3/libraries

And you can test the API call from the doc:

您可以从文档中测试 API 调用:

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

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

Sample:

样本:

Request:

要求:

GET https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Q5mHPo2yDG8&key={YOUR_API_KEY}

Authorization:  Bearer ya29.AHES6ZSCT9BmIXJmjHlRlKMmVCU22UQzBPRuxzD7Zg_09hsG
X-JavaScript-User-Agent:  Google APIs Explorer

Response:

回复:

200 OK

- Show headers -

{
 "kind": "youtube#videoListResponse",
 "etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/dZ8K81pnD1mOCFyHQkjZNynHpYo\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {

   "id": "Q5mHPo2yDG8",
   "kind": "youtube#video",
   "etag": "\"g-RLCMLrfPIk8n3AxYYPPliWWoo/4NA7C24hM5mprqQ3sBwI5Lo9vZE\"",
   "statistics": {
    "viewCount": "36575966",
    "likeCount": "127569",
    "dislikeCount": "5715",
    "favoriteCount": "0",
    "commentCount": "20317"
   }
  }
 ]
}

回答by steffanjj

Version 2 of the API has been deprecated since March 2014, which some of these other answers are using.

API 的第 2 版自 2014 年 3 月起已被弃用,其中一些其他答案正在使用。

Here is a very simple code snippet to get the views count from a video, using JQuery in the YouTube API v3.

这是一个非常简单的代码片段,用于从视频中获取观看次数,使用 YouTube API v3 中的 JQuery。

You will need to create an API key via Google Developer Consolefirst.

您需要先通过Google Developer Console创建 API 密钥。

<script>
  $.getJSON('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Qq7mpb-hCBY&key={{YOUR-KEY}}', function(data) {
    alert("viewCount: " + data.items[0].statistics.viewCount);
  });
</script>

回答by SVS

Here is a small code snippet to get Youtube video views from URL using Javascript

这是一个小代码片段,用于使用 Javascript 从 URL 获取 Youtube 视频视图

Demo of below code

下面代码演示

    function videoViews() {
var rex = /[a-zA-Z0-9\-\_]{11}/,
    videoUrl = $('input').val() === '' ? alert('Enter a valid Url'):$('input').val(),
    videoId = videoUrl.match(rex),
    jsonUrl = 'http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=json',
   embedUrl = '//www.youtube.com/embed/' + videoId,
   embedCode = '<iframe width="350" height="197" src="' + embedUrl + '" frameborder="0" allowfullscreen></iframe>'


//Get Views from JSON
$.getJSON(jsonUrl, function (videoData) {
    var videoJson = JSON.stringify(videoData),
        vidJson = JSON.parse(videoJson),
        views = vidJson.entry.yt$statistics.viewCount;
    $('.views').text(views);
});

//Embed Video
$('.videoembed').html(embedCode);}

回答by NVRM

Why using any api keyto retrieve a portion of public html!

为什么使用任何api 密钥来检索公共 html 的一部分!

Simplest unix command line demonstrative example, using curl, grepand cut.

最简单的 unix 命令行演示示例,使用curlgrepcut

curl https://www.youtube.com/watch?v=r-y7jzGxKNo | grep watch7-views-info | cut -d">" -f8 | cut -d"<" -f1

Yes, it get the full html page, this loss has no meaning against the countless advantages.

是的,它获得了完整的 html 页面,这种损失与无数优势相比毫无意义。

回答by dragos

You can use this too:

你也可以使用这个:

<?php
    $youtube_view_count = json_decode(file_get_contents('http://gdata.youtube.com/feeds/api/videos/wGG543FeHOE?v=2&alt=json'))->entry->{'yt$statistics'}->viewCount;
    echo $youtube_view_count;
    ?>

回答by zmonteca

Use the Google PHP API Client: https://github.com/google/google-api-php-client

使用 Google PHP API 客户端:https: //github.com/google/google-api-php-client

Here's a little mini class just to get YouTube statistics for a single video id. It can obviously be extended a ton using the remainder of the api: https://api.kdyby.org/class-Google_Service_YouTube_Video.html

这是一个小类,只是为了获取单个视频 ID 的 YouTube 统计信息。它显然可以使用 api 的其余部分扩展一吨:https: //api.kdyby.org/class-Google_Service_YouTube_Video.html

class YouTubeVideo
{
    // video id
    public $id;

    // generate at https://console.developers.google.com/apis
    private $apiKey = 'REPLACE_ME';

    // google youtube service
    private $youtube;

    public function __construct($id)
    {
        $client = new Google_Client();
        $client->setDeveloperKey($this->apiKey);

        $this->youtube = new Google_Service_YouTube($client);

        $this->id = $id;
    }

    /*
     * @return Google_Service_YouTube_VideoStatistics
     * Google_Service_YouTube_VideoStatistics Object ( [commentCount] => 0 [dislikeCount] => 0 [favoriteCount] => 0 [likeCount] => 0 [viewCount] => 5 )  
     */
    public function getStatistics()
    {
        try{
            // Call the API's videos.list method to retrieve the video resource.
            $response = $this->youtube->videos->listVideos("statistics",
                array('id' => $this->id));

            $googleService = current($response->items);
            if($googleService instanceof Google_Service_YouTube_Video) {
                return $googleService->getStatistics();
            }
        } catch (Google_Service_Exception $e) {
            return sprintf('<p>A service error occurred: <code>%s</code></p>',
                htmlspecialchars($e->getMessage()));
        } catch (Google_Exception $e) {
            return sprintf('<p>An client error occurred: <code>%s</code></p>',
                htmlspecialchars($e->getMessage()));
        }
    }
}

回答by Devner

Here is a simple function in PHPthat returns the number of views a YouTube video has. You will need the YouTube Data API Key (v3) in order for this to work. If you don't have the key, get one for free at: YouTube Data API

这是PHP中的一个简单函数,用于返回 YouTube 视频的观看次数。您将需要 YouTube 数据 API 密钥 (v3) 才能使其正常工作。如果您没有密钥,请通过以下网址免费获取:YouTube Data API

//Define a constant so that the API KEY can be used globally across the application    
define("YOUTUBE_DATA_API_KEY", 'YOUR_YOUTUBE_DATA_API_KEY');

function youtube_video_statistics($video_id) {
    $json = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=" . $video_id . "&key=". YOUTUBE_DATA_API_KEY );
    $jsonData = json_decode($json);
    $views = $jsonData->items[0]->statistics->viewCount;
    return $views;
}

//Replace YOUTUBE_VIDEO_ID with your actual YouTube video Id
echo youtube_video_statistics('YOUTUBE_VIDEO_ID');

I am using this solution in my application and it is working as of today. So get the API Key and YouTube video ID and replace them in the above code (Second Line and Last Line) and you should be good to go.

我在我的应用程序中使用了这个解决方案,它从今天开始工作。因此,获取 API Key 和 YouTube 视频 ID 并将它们替换为上面的代码(第二行和最后一行),然后就可以了。

回答by Shahzaib Chadhar

PHP JSON

PHP JSON

$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id=$Videoid&key={YOUR-API-KEY}&part=statistics");
$json = json_decode($jsonURL);

First go through this one by uncommenting

首先通过取消注释来完成这个

//var_dump(json);

and get views count as:

并获得观看次数为:

$vcounts = $json->{'items'}[0]->{'statistics'}->{'viewCount'};