首页 > 解决方案 > 更改视频标题时出现 Youtube 数据 api 错误

问题描述

为什么我在下面给出的脚本上收到此错误:

Traceback (most recent call last):
  File "C:\Path\YoutubeApi\main.py", line 54, in <module>
    main()
  File "C:\Path\YoutubeApi\main.py", line 49, in main
    response = request.execute()
  File "C:\Users\$user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\googleapiclient\_helpers.py", line 131, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\$user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\googleapiclient\http.py", line 937, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/videos?part=snippet&alt=json returned "The <code>snippet.categoryId</code> property specifies an invalid category ID. Use the <code><a href="/youtube/v3/docs/videoCategories/list">videoCategories.list</a></code> method to retrieve supported categories.". Details: "[{'message': 'The <code>snippet.categoryId</code> property specifies an invalid category ID. Use the <code><a href="/youtube/v3/docs/videoCategories/list">videoCategories.list</a></code> method to retrieve supported categories.', 'domain': 'youtube.video', 'reason': 'invalidCategoryId', 'location': 'body.snippet.categoryId', 'locationType': 'other'}]">

主文件

import os
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build

def main():
    credentials = None
    # token.pickle stores the user's credentials from previously successful logins
    if os.path.exists('token.pickle'):
        print('Loading Credentials From File...')
        with open('token.pickle', 'rb') as token:
            credentials = pickle.load(token)

    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            print('Refreshing Access Token...')
            credentials.refresh(Request())
        else:
            print('Fetching New Tokens...')
            flow = InstalledAppFlow.from_client_secrets_file(
                'client_secrets.json',
                scopes=[
                    'https://www.googleapis.com/auth/youtube.force-ssl'
                ]
            )

            flow.run_local_server(port=8080, prompt='consent',
                                authorization_prompt_message='')
            credentials = flow.credentials

            # Save the credentials for the next run
            with open('token.pickle', 'wb') as f:
                print('Saving Credentials for Future Use...')
                pickle.dump(credentials, f)

    youtube = build('youtube','v3',credentials=credentials)

    request = youtube.videos().update(
        part = 'snippet',
        body={
            "id": "OSxK-tscmVA",
            "snippet":{
                "title":"It's changed",
            }
        }
    )
    

    response = request.execute()

    print(response)

if __name__ == '__main__':
    main()

脚本说明:

该脚本的作用是,如果没有名为 token.pickle 的文件,它将要求用户授权应用程序,并且脚本会将用户凭据存储在 token.pickle 文件中,这样用户就不必在每个单次运行,脚本的第 2 部分更改了我的 YouTube 视频的标题。

标签: python-3.xyoutube-apiyoutube-data-api

解决方案


不幸的是,您似乎不倾向于使用Videos.updateAPI 端点的官方规范:

您对端点的调用的请求正文也需要指定视频类别 ID才能被 API 后端接受。

请注意,update_video.py来自 Google 的示例代码(我在您的系列文章开头指出您作为有价值的信息来源)包含所有这些必需的东西。

再次,请承认您必须吸收(即理解)该代码。除了仔细阅读官方文档之外别无他法。


推荐阅读