我开始考虑将 YouTube API 与 python 结合使用,但文档中给出的示例似乎与快速入门指南不一致。
可以找到快速入门指南 here在其中,他们建议您从 API 文档中获取一些示例代码 here将从 API 请求“YouTube 开发者” channel 的一些信息。现在在快速入门指南中,他们说用您的 API key 替换“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 google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
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.channels().list(
part="snippet,contentDetails,statistics",
id="UC_x5XG1OV2P6uZZ5FSM9Ttw"
)
response = request.execute()
print(response)
if __name__ == "__main__":
main()
我认为“YOUR_CLIENT_SECRET_FILE”字符串仅适用于需要用户身份验证的请求,这种类型的请求不应该是这种情况。
那么您应该在哪里提供 API key ?该指南是否已过时?
非常感谢所有帮助!
请您参考如下方法:
- 您想通过 YouTube 数据 API v3 使用 API key 检索 channel 列表。
- 您已经拥有使用 YouTube 数据 API v3 的 API。
- 你想用 Python 实现这个 google-api-python-client。
- 您已经能够使用 YouTube Data API v3。
如果我的理解是正确的,这个示例脚本怎么样?
示例脚本:
在使用此脚本之前,请设置您的 API key 。
from googleapiclient.discovery import build
api_key = "###" # Please set your API key
api_service_name = "youtube"
api_version = "v3"
youtube = build(api_service_name, api_version, developerKey=api_key)
request = youtube.channels().list(
part="snippet,contentDetails,statistics",
id="UC_x5XG1OV2P6uZZ5FSM9Ttw"
)
response = request.execute()
print(response)
备注:
- 此示例脚本假设您已经能够使用 YouTube Data API v3。如果出现API相关错误,请确认API是否开启。
引用:
- google-api-python-client
- 特别是,我认为 here将有助于了解如何使用 API key 。
如果我误解了您的问题并且这不是您想要的结果,我深表歉意。
