首页 > 解决方案 > 从 youtube api 复制代码后,我不确定从哪里继续

问题描述

我目前正在阅读本指南以开始使用 youtube api:https ://developers.google.com/youtube/v3/quickstart/python在我复制他们的示例代码的第 2 步中,指令说要复制我的 api 密钥和替换示例代码中的 YOUR_API_KEY 字符串。但是示例代码中没有 YOUR_API_KEY

这是他们提供的示例代码,我找不到 api_key 部分。我已经有我的 client_secret.json 文件但是当我替换 client_secrets_file 它仍然不会执行

# -*- coding: utf-8 -*-

# Sample Python code for youtube.search.list
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/guides/code_samples#python

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="snippet",
        maxResults=25,
        q="surfing"
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

标签: pythonyoutube-data-api

解决方案


快速入门指南似乎不是最新的。它说应该有一个“凭据”下拉菜单,您应该在其中选择“API 密钥”以获取使用 API 密钥的代码示例,但没有这样的下拉菜单。

相反,在您获得示例代码的地方,您需要取消选中“Google OAuth 2.0”框。(我也必须编辑和取消编辑“部分”字段以使代码刷新。)这会产生以下不同的示例代码,其中包含预期的YOUR_API_KEY占位符:

# -*- coding: utf-8 -*-

# Sample Python code for youtube.channels.list
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/guides/code_samples#python

import os

import googleapiclient.discovery

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    DEVELOPER_KEY = "YOUR_API_KEY"

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, developerKey = DEVELOPER_KEY)

    request = youtube.channels().list(
        part="snippet,contentDetails,statistics",
        id="UC_x5XG1OV2P6uZZ5FSM9Ttw"
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()

然后您可以填写您自己的 API 密钥。


推荐阅读