Programing

YouTube API로 동영상 조회수를 얻는 방법은 무엇입니까?

lottogame 2020. 10. 10. 09:28
반응형

YouTube API로 동영상 조회수를 얻는 방법은 무엇입니까?


질문은 매우 간단합니다. YouTube API로 동영상 조회수를 얻는 방법은 무엇입니까?

여기에 이미지 설명 입력

작업은 간단하지만 많은 수의 비디오에 대해이 쿼리를 자주 사용하고 싶습니다. Youtube API를 호출하여 얻을 수있는 방법이 있습니까? (facebook http://api.facebook.com/restserver.php?method=links.getStats&urls=developers.facebook.com 과 같은 것 )


가장 쉬운 방법은 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;
?>

참조 : Youtube API-단일 비디오에 대한 정보 검색


새로운 YouTube Data API v3를 사용할 수 있습니다.

비디오를 검색하는 경우 통계 부분에는 viewCount 가 포함 됩니다 .

문서에서 :

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

statistics.viewCount / 동영상을 본 횟수입니다.

클라이언트 측 또는 일부 클라이언트 라이브러리를 사용하여 서버 측에서이 정보를 검색 할 수 있습니다.

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

문서에서 API 호출을 테스트 할 수 있습니다.

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

견본:

의뢰:

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

응답:

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"
   }
  }
 ]
}

API의 버전 2는 2014 년 3 월 이후로 더 이상 사용되지 않으며 이러한 다른 답변 중 일부가 사용하고 있습니다.

다음은 YouTube API v3에서 JQuery를 사용하여 동영상에서 조회수를 가져 오는 매우 간단한 코드 스 니펫입니다.

먼저 Google 개발자 콘솔을 통해 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>

다음은 자바 스크립트를 사용하여 URL에서 YouTube 동영상 조회수를 가져 오는 작은 코드 스 니펫입니다.

아래 코드 데모

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

이것도 사용할 수 있습니다.

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

Google PHP API 클라이언트 사용 : https://github.com/google/google-api-php-client

단일 동영상 ID에 대한 YouTube 통계를 얻기위한 간단한 미니 클래스가 있습니다. https://api.kdyby.org/class-Google_Service_YouTube_Video.html 의 나머지 API를 사용하여 분명히 확장 할 수 있습니다.

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

공개 html의 일부를 검색하기 위해 API 키사용하는 이유 !

curl , grepcut을 사용하는 가장 간단한 유닉스 명령 줄 시연 예제 .

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

예, 전체 HTML 페이지를 얻습니다.이 손실은 수많은 이점에 대해 의미가 없습니다.


yt:statistics태그를 보세요 . 그것은 제공 viewCount, videoWatchCount, favoriteCount


여기 내 TubeCount 앱 에서 사용한 예가 있습니다 .

I also use the fields parameter to filter the JSON result, so only the fields that I need are returned.

var fields = "fields=openSearch:totalResults,entry(title,media:group(yt:videoid),media:group(yt:duration),media:group(media:description),media:group(media:thumbnail[@yt:name='default'](@url)),yt:statistics,yt:rating,published,gd:comments(gd:feedLink(@countHint)))";

var channel = "wiibart";

$.ajax({
    url: "http://gdata.youtube.com/feeds/api/users/"+channel+"/uploads?"+fields+"&v=2&alt=json",
    success: function(data){

        var len = data.feed.entry.length;

        for(var k =0; k<len; k++){
            var yt = data.feed.entry[k];
            v.count = Number(yt.yt$statistics != undefined && yt.yt$statistics.viewCount != undefined ? yt.yt$statistics.viewCount : 0);
        }
    }
});

Here is a simple function in PHP that 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

//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.


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'};

YouTube Data API v3 URL Sample

Source Link

https://www.googleapis.com/youtube/v3/videos?key=[YOUR_API_KEY_HERE]&fields=items(snippet(title,tags,channelTitle,publishedAt),statistics(viewCount))&part=snippet,statistics&id=[VIDEOID]


JQuery를 사용할 수 있으며 Your-Api-Key아래 코드에서 문자열 을 바꾸는 것을 잊지 말고 링크를 따라 자신의 Api 키를 찾으십시오 .Google 개발자 콘솔

<script>
    $.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
        console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
    });
</script>

이것은 아마도 원하는 것이 아니지만 다음을 사용하여 정보에 대한 페이지를 스크랩 할 수 있습니다.

document.getElementsByClassName('watch-view-count')[0].innerHTML

참고 URL : https://stackoverflow.com/questions/3331176/how-to-get-number-of-video-views-with-youtube-api

반응형