Youtube API v3和python在自己的YouTube视频上生成视图/喜欢的列表

问题描述 投票:0回答:3

我正在尝试使用基于RaspberryPi3 Python的鸟舍来阅读其上传视频的受欢迎程度(这使得它能够删除哪些应该被删除并避免数百个上传的文件)。我认为阅读#views / #like的最佳方式是使用yt_analytics_report.py

当我输入它时总是返回0值:

当我输入:

$python yt_analytics_report.py --filters="video==bb_o--nP1mg"

要么

$python yt_analytics_report.py --filters="channel==UCGXIq7h2UeFh9RhsSEsFsiA"

输出是:

$ python yt_analytics_report.py --filters =“video == bb_o - nP1mg”{'metrics':'views,estimatedMinutesWatched,averageViewDuration','filters':'video == bb_o - nP1mg','ids':' channel == MINE','end_date':'2018-01-12','start_date':'2018-01-06'} 请访问此URL以授权此应用程序:[注意:这里是我认可的真实序列等的URL],然后是结果: viewsMinutesWatched averageViewDuration 0.0 0.0 0.0

我是新来的;过去3天我一直在测试各种过滤器,但结果总是一样的。我想我做了一件严重的错事。 (自动传感器触发)视频上传工作非常出色,因此我认为根本原因与我使用yt-analytics示例的方式有关。任何关于rootcause或替代方法的建议,以检索自己上传的youtubes#views / #like赞赏。

python google-api youtube-api raspberry-pi3 youtube-data-api
3个回答
3
投票

经过几天的尝试,我找到了一个解决方案,如何使用Python和Youtube API v3生成一个列表,其中包含我自己的Youtube频道上传视频的视图,喜欢等。我想分享完整的代码,万一有人遇到同样的挑战。该代码包含备注和引用其他信息。请注意,使用API​​会消耗API信用额......这意味着(当您持续或经常运行此脚本时),您可能会用完Google设置的每日最大API信用数。

# This python 2.7.14 example shows how to retrieve with Youtube API v3 a list of uploaded Youtube videos in a channel and also
# shows additional statistics of each individual youtube video such as number of views, likes etc.
# Please notice that YOU HAVE TO change API_KEY and Youtube channelID
# Have a look at the referred examples to get to understand how the API works
#
# The code consists of two parts:
# - The first part queries the videos in a channel and stores it in a list
# - The second part queries in detail each individual video
#
# Credits to the Coding 101 team, the guy previously guiding me to a query and Google API explorer who/which got me on track.
#
# RESULTING EXAMPLE OUTPUT: The output of the will look a bit like this:
#
# https://www.youtube.com/watch?v=T3U2oz_Y8T0
# Upload date:        2018-01-13T09:43:27.000Z
# Number of views:    8
# Number of likes:    2
# Number of dislikes: 0
# Number of favorites:0
# Number of comments: 0
#
# https://www.youtube.com/watch?v=EFyC8nhusR8
# Upload date:        2018-01-06T14:24:34.000Z
# Number of views:    6
# Number of likes:    2
# Number of dislikes: 0
# Number of favorites:0
# Number of comments: 0
#
#
import urllib #importing to use its urlencode function
import urllib2 #for making http requests
import json #for decoding a JSON response
#
API_KEY = 'PLACE YOUR OWN YOUTUBE API HERE'                 # What? How? Learn here: https://www.youtube.com/watch?v=JbWnRhHfTDA 
ChannelIdentifier = 'PLACE YOUR OWN YOUTUBE channelID HERE' # What? How? Learn here: https://www.youtube.com/watch?v=tf42K4pPWkM
#
# This first part will query the list of videos uploaded of a specific channel
# The identification is done through the ChannelIdentifier hwich you have defined as a variable
# The results from this first part will be stored in the list videoMetadata. This will be used in the second part of the code below.
#
# This code is based on the a very good example from Coding 101 which you can find here:https://www.youtube.com/watch?v=_M_wle0Iq9M
#
url = 'https://www.googleapis.com/youtube/v3/search?part=snippet&channelId='+ChannelIdentifier+'&maxResults=50&type=video&key='+API_KEY
response = urllib2.urlopen(url) #makes the call to YouTube
videos = json.load(response) #decodes the response so we can work with it
videoMetadata = [] #declaring our list
for video in videos['items']:
  if video['id']['kind'] == 'youtube#video':
      videoMetadata.append(video['id']['videoId']) #Appends each videoID and link to our list
#
# In this second part, a loop will run through the listvideoMetadata
# During each step the details a specific video are retrieved and displayed
# The structure of the API-return can be tested with the API explorer (which you can excecute without OAuth):
# https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.videos.list?part=snippet%252CcontentDetails%252Cstatistics&id=Ks-_Mh1QhMc&_h=1&
#
for metadata in videoMetadata:
  print "https://www.youtube.com/watch?v="+metadata  # Here the videoID is printed
  SpecificVideoID = metadata
  SpecificVideoUrl = 'https://www.googleapis.com/youtube/v3/videos?part=snippet%2CcontentDetails%2Cstatistics&id='+SpecificVideoID+'&key='+API_KEY
  response = urllib2.urlopen(SpecificVideoUrl) #makes the call to a specific YouTube
  videos = json.load(response) #decodes the response so we can work with it
  videoMetadata = [] #declaring our list
  for video in videos['items']: 
    if video['kind'] == 'youtube#video':
        print "Upload date:        "+video['snippet']['publishedAt']    # Here the upload date of the specific video is listed
        print "Number of views:    "+video['statistics']['viewCount']   # Here the number of views of the specific video is listed
        print "Number of likes:    "+video['statistics']['likeCount']   # etc
        print "Number of dislikes: "+video['statistics']['dislikeCount']
        print "Number of favorites:"+video['statistics']['favoriteCount']
        print "Number of comments: "+video['statistics']['commentCount']
        print "\n"

0
投票

基于Sefo上面的答案,我能够稍微清理一下输出。

第一个函数创建一个相关视频列表(您可以根据需要替换它),第二个函数遍历此列表并获取与每个视频相关的统计信息和基本文本数据。

输出是一个字典列表,非常适合转换为pandas DataFrame。

def youtube_search_list(q, max_results=10):
  # Call the search.list method to retrieve results matching the specified
  # query term.
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results matching the specified
  # query term.
    search_response = youtube.search().list(
        q=q,
        part='id,snippet',
        maxResults=max_results,
        order='viewCount'
      ).execute()

    return search_response

def youtube_search_video(q='spinners', max_results=10):
    max_results = max_results
    order = "viewCount"
    token = None
    location = None
    location_radius = None
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,         
    developerKey=DEVELOPER_KEY)
    q=q
    #Return list of matching records up to max_search
    search_result = youtube_search_list(q, max_results)

    videos_list = []
    for search_result in search_result.get("items", []):

        if search_result["id"]["kind"] == 'youtube#video':
            temp_dict_ = {}
            #Available from initial search
            temp_dict_['title'] = search_result['snippet']['title']  
            temp_dict_['vidId'] = search_result['id']['videoId']  

            #Secondary call to find statistics results for individual video
            response = youtube.videos().list(
                part='statistics, snippet', 
                id=search_result['id']['videoId']
                    ).execute()  
            response_statistics = response['items'][0]['statistics']
            response_snippet = response['items'][0]['snippet']


            snippet_list = ['publishedAt','channelId', 'description', 
                            'channelTitle', 'tags', 'categoryId', 
                            'liveBroadcastContent', 'defaultLanguage', ]
            for val in snippet_list:
                try:
                    temp_dict_[val] = response_snippet[val]
                except:
                    #Not stored if not present
                    temp_dict_[val] = 'xxNoneFoundxx'    

            stats_list = ['favoriteCount', 'viewCount', 'likeCount', 
                          'dislikeCount', 'commentCount']
            for val in stats_list:
                try:
                    temp_dict_[val] = response_statistics[val]
                except:
                    #Not stored if not present
                    temp_dict_[val] = 'xxNoneFoundxx'

            #add back to main list
            videos_list.append(temp_dict_)

    return videos_list

-1
投票

这段代码对你有所帮助,我很长时间都在苦苦挣扎,只需在googleapiclient.discovery import build的搜索列表中提供API密钥和youtube频道名称以及频道ID

DEVELOPER_KEY = "paste your API key here"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
title = []
channelId = []
channelTitle = []
categoryId = []
videoId = []
viewCount = []
likeCount = []
dislikeCount = []
commentCount = []
favoriteCount = []
category = []
tags = []
videos = []
tags = []
max_search = 50
order = "relevance"
token = None
location = None
location_radius = None
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,         
developerKey=DEVELOPER_KEY)
search_result = youtube.search().list(q="put the channel name here", type="video",     
pageToken=token, order=order, part="id,snippet",
                                  maxResults=max_search, location=location,
                                  locationRadius=location_radius, channelId='put the     
channel ID here').execute()  # this line is to get the videos of the channel by the 
name of it
for search_result in search_result.get("items", []):
if search_result["id"]["kind"] == 'youtube#video':
    title.append(search_result['snippet']['title'])  # the title of the video
    videoId.append(search_result['id']['videoId'])  # the ID of the video
    response = youtube.videos().list(part='statistics, snippet',     
id=search_result['id'][
        'videoId']).execute()  # this is the other request because the statistics and     
snippet require this because of the API
    channelId.append(response['items'][0]['snippet']['channelId'])  # channel ID, 
which is constant here
    channelTitle.append(response['items'][0]['snippet']['channelTitle'])    # channel 
title, also constant
    categoryId.append(response['items'][0]['snippet']['categoryId'])        # stores 
the categories of the videos
    favoriteCount.append(response['items'][0]['statistics']['favoriteCount'])   # 
stores the favourite count of the videos
    viewCount.append(response['items'][0]['statistics']['viewCount'])           # 
stores the view counts
    """  

    the likes and dislikes had a bug all along, which required the if else instead of 
just behaving like the viewCount"""
    if 'likeCount' in response['items'][0]['statistics'].keys():             # checks 
for likes count then restores it, if no likes stores 0
        likeCount.append(response['items'][0]['statistics']['likeCount'])
    else:
        likeCount.append('0')
    if 'dislikeCount' in response['items'][0]['statistics'].keys():             # checks for dislikes count then stores it, if no dislikes found returns 0
        dislikeCount.append(response['items'][0]['statistics']['dislikeCount'])
    else:
        likeCount.append('0')
    if 'commentCount' in response['items'][0]['statistics'].keys():             # checks for comment count then stores it, if no comment found stores 0
        commentCount.append(response['items'][0]['statistics']['commentCount'])
    else:
        commentCount.append('0')
    if 'tags' in response['items'][0]['snippet'].keys():                        # checks for tags count then stores it, if none found stores 0
        tags.append(response['items'][0]['snippet']['tags'])
    else:
        tags.append('0')
youtube_dict = {
'tags': tags,
'channelId': channelId,
'channelTitle': channelTitle,
'categoryId': categoryId,
'title': title,
'videoId': videoId,
'viewCount': viewCount,
'likeCount': likeCount,
'dislikeCount': dislikeCount,
'commentCount': commentCount,
'favoriteCount': favoriteCount
}
for x in youtube_dict:
print(x)
for y in youtube_dict[x]:
    print(y)

请重新缩进代码,因为该网站破坏了python的缩进,使代码部分中的代码不在单词部分。祝好运

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