python - 检索 youtube 订阅 python api

标签 python youtube-api youtube-data-api

我想使用 youtube-api 使用 python(不显示)从命令行检索我的 YouTube 订阅列表和其他数据,在阅读 google 开发人员文档后,我意识到 ouath 2 需要用户界面,但还有一个 plugin可用于使用 youtube tv 与 youtube 交互的 kodi,我认为它对我的情况很有用。

最佳答案

正如您所提到的,为了检索您的订阅列表,您需要首先验证并授权您的应用程序或脚本“读取”您的订阅。完成此操作后,您将能够使用 YouTube 订阅数据 API 列表方法检索您的 YouTube 订阅: Subscriptions: list

使用 YouTube 订阅数据 API 插入方法的 Python 示例代码的修改版本 Subscriptions: insert以下代码将对用户进行身份验证和授权,然后在获得授权后检索授权用户的所有 YouTube 订阅。

虽然下面的代码没有显式地使用命令行参数工作,但如果您选择使用它们,那么它没有理由不应该使用命令行参数工作。几个 Google YouTube API Python 示例都有实现此效果的代码。

# coding: utf-8
# https://developers.google.com/youtube/v3/docs/subscriptions/list

import math
import os
import sys

import httplib2
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google Developers Console at
# https://console.developers.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"

# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
YOUTUBE_READ_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you will need to populate the client_secrets.json file
found at:

   {}

with information from the Developers Console
https://console.developers.google.com/

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""".format(os.path.abspath(os.path.join(os.path.dirname(__file__),
                                        CLIENT_SECRETS_FILE)))


def retrieve_youtube_subscriptions():
    # In order to retrieve the YouTube subscriptions for the current user,
    # the user needs to authenticate and authorize access to their YouTube
    # subscriptions.
    youtube_authorization = get_authenticated_service()

    try:
        # init
        next_page_token = ''
        subs_iteration = 0
        while True:
            # retrieve the YouTube subscriptions for the authorized user
            subscriptions_response = youtube_subscriptions(youtube_authorization, next_page_token)
            subs_iteration += 1
            total_results = subscriptions_response['pageInfo']['totalResults']
            results_per_page = subscriptions_response['pageInfo']['resultsPerPage']
            total_iterations = math.ceil(total_results / results_per_page)
            print('Subscriptions iteration: {} of {} ({}%)'.format(subs_iteration,
                                                                   total_iterations,
                                                                   round(subs_iteration / total_iterations * 100),
                                                                   0))
            # get the token for the next page if there is one
            next_page_token = get_next_page(subscriptions_response)
            # extract the required subscription information
            channels = parse_youtube_subscriptions(subscriptions_response)
            # add the channels relieved to the main channel list
            all_channels.extend(channels)
            if not next_page_token:
                break
        return all_channels

    except HttpError as err:
        print("An HTTP error {} occurred:\n{}".format(err.resp.status, err.content))


def get_authenticated_service():
    # Create a Storage instance to store and retrieve a single
    # credential to and from a file. Used to store the
    # oauth2 credentials for the current python script.
    storage = Storage("{}-oauth2.json".format(sys.argv[0]))
    credentials = storage.get()

    # Validate the retrieved oauth2 credentials
    if credentials is None or credentials.invalid:
        # Create a Flow instance from a client secrets file
        flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
                                       scope=YOUTUBE_READ_WRITE_SCOPE,
                                       message=MISSING_CLIENT_SECRETS_MESSAGE)
        # The run_flow method requires arguments.
        # Initial default arguments are setup in tools, and any
        # additional arguments can be added from the command-line
        # and passed into this method.
        args = argparser.parse_args()
        # Obtain valid credentials
        credentials = run_flow(flow, storage, args)

    # Build and return a Resource object for interacting with an YouTube API
    return build(YOUTUBE_API_SERVICE_NAME,
                 YOUTUBE_API_VERSION,
                 http=credentials.authorize(httplib2.Http()))


# Call youtube.subscriptions.list method
# to list the channels subscribed to.
def youtube_subscriptions(youtube, next_page_token):
    subscriptions_response = youtube.subscriptions().list(
        part='snippet',
        mine=True,
        maxResults=50,
        order='alphabetical',
        pageToken=next_page_token).execute()
    return subscriptions_response


def get_next_page(subscriptions_response):
    # check if the subscription response contains a reference to the
    # next page or not
    if 'nextPageToken' in subscriptions_response:
        next_page_token = subscriptions_response['nextPageToken']
    else:
        next_page_token = ''
    return next_page_token


def parse_youtube_subscriptions(subscriptions_response):
    channels = []

    # Add each result to the appropriate list
    for subscriptions_result in subscriptions_response.get("items", []):
        if subscriptions_result["snippet"]["resourceId"]["kind"] == "youtube#channel":
            channels.append("{} ({})".format(subscriptions_result["snippet"]["title"],
                                             subscriptions_result["snippet"]["resourceId"]["channelId"]))

    return channels


if __name__ == "__main__":
    # init
    all_channels = []

    print('Perform youtube subscriptions')
    # retrieve subscriptions
    all_channels = retrieve_youtube_subscriptions()
    print('Subscriptions complete')
    print('Subscriptions found: {}'.format(len(all_channels)))

    print("Channels:\n", "\n".join(all_channels), "\n")

注意:作为一次性操作,上述代码如果未找到用户的授权凭据,将打开本地 URL 并重定向到 Google 进行身份验证。

其他先决条件:

  1. 要使上述 Python 3 代码正常运行,需要使用 pip 安装“google-api-python-client-py3”软件包。
  2. 需要创建 client_secrets.json 文件。这是通过遵循 python 脚本顶部的说​​明来完成的。

关于python - 检索 youtube 订阅 python api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37755678/

相关文章:

python - gdata youtube api 302 'The document has moved'

java - Youtube api v3 - 如何检索标记为垃圾邮件的评论(使用java)

python - check_call check_output 调用和子进程模块中的 Popen 方法之间的实际区别是什么?

python - 我*必须*在我的数据库中存储第三方凭证。最好的办法?

youtube-api - YouTube API : Get upload playlistID for YouTube Channel

html - 您可以从 youtube 中提取/引入视频的评级以用于您自己的网站吗?

youtube - 使用Youtube API使用字符串设置视频标签

api - YouTube API返回空项目列表

python - Matlab k-means cosine 将所有内容分配给一个簇

python - 从嵌套字典创建文件树 | Python 2.7