python Youtube数据API v3 -跳过“请访问此URL”&输入授权码?

icnyk63a  于 2023-02-11  发布在  Python
关注(0)|答案(1)|浏览(166)

我试图得到我的youtube频道的视频列表,并更新它,因为我请,我已经做了它与.net &这是相当容易的,但在python这是一种令人不安的每次我运行脚本,我得到的消息“请访问此URL授权此应用程序”虽然我使用相同的credentials.json文件,我用它在. net.
注:没有必要标记这个问题的重复或任何东西,因为我已经检查了许多相同的问题在这里的堆栈像thisthisthis其他论坛太多,但似乎没有提供一个明确的具体解决方案,到目前为止,我已经尝试了每个解决方案都有相同的结果。
下面是我使用的示例代码:
任何帮助都将不胜感激。

import os
import sys
file_path = os.path.dirname(__file__)
module_path = os.path.join(file_path, "lib")
sys.path.append(module_path)
import pickle
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
scopes = [
    "https://www.googleapis.com/auth/youtube",
    "https://www.googleapis.com/auth/youtube.upload",
    "https://www.googleapis.com/auth/youtubepartner",
    "https://www.googleapis.com/auth/youtube.force-ssl",
    ]
client_secrets_file = "credentials.json"
api_service_name = "youtube"
api_version = "v3"

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    youtube = get_authenticated_service()
    request = youtube.channels().list(
        part="contentDetails",
        mine=True
    )
    response = request.execute()
    print(response)

def get_authenticated_service():
    if os.path.exists("CREDENTIALS_PICKLE_FILE"):
        with open("CREDENTIALS_PICKLE_FILE", 'rb') as f:
            credentials = pickle.load(f)
    else:
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes)
        credentials = flow.run_console()
        with open("CREDENTIALS_PICKLE_FILE", 'wb') as f:
            pickle.dump(credentials, f)
    return googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)
if __name__ == "__main__":
    main()
a1o7rhls

a1o7rhls1#

我很幸运地找到了这个问题的解决方案,这里有一个工作脚本示例,它将列出您在您的YouTube频道中的所有视频,并将要求授权代码只一次。
我知道这有点乱不过没关系

import os
import sys
file_path = os.path.dirname(__file__)
module_path = os.path.join(file_path, "lib")
sys.path.append(module_path)
import httplib2
import json
import argparse
import re
import random
from pytz import timezone
from dateutil import parser
from datetime import datetime
from googleapiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

random.seed()
CLIENT_SECRETS_FILE = "credentials.json"
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:   %swith information from the Developers Console
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),CLIENT_SECRETS_FILE))

scopes = [
    "https://www.googleapis.com/auth/youtube",
    "https://www.googleapis.com/auth/youtube.upload",
    "https://www.googleapis.com/auth/youtubepartner",
    "https://www.googleapis.com/auth/youtube.force-ssl",
    ]
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,message=MISSING_CLIENT_SECRETS_MESSAGE, scope=scopes)

storage = Storage("%s-oauth2.json" % sys.argv[0])
credentials = storage.get()
if credentials is None or credentials.invalid:
  flags = argparser.parse_args()
  credentials = run_flow(flow, storage, flags)

youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
  http=credentials.authorize(httplib2.Http()))

channels_response = youtube.channels().list(
  mine=True,
  part="contentDetails"
).execute()

for channel in channels_response["items"]:
  uploads_list_id = channel["contentDetails"]["relatedPlaylists"]["uploads"]
  print("Videos in list {0:s}".format(uploads_list_id),file=sys.stderr)
  playlistitems_list_request = youtube.playlistItems().list(
    playlistId=uploads_list_id,
    part="snippet",
    maxResults=50
  )

playlistitems_list_response = playlistitems_list_request.execute()

for playlist_item in playlistitems_list_response["items"]:
    title = playlist_item["snippet"]["title"]
    video_id = playlist_item["snippet"]["resourceId"]["videoId"]
    video_list_request = youtube.videos().list(
    id=video_id,
    part="snippet,fileDetails,statistics,status",
    maxResults=50
    )
    video_list_response = video_list_request.execute()
    for video_list_item in video_list_response["items"]:
        print(title)
        print (video_id)
        print (video_list_item["fileDetails"]["fileName"])
        print (video_list_item["statistics"]["viewCount"])
        print (video_list_item["statistics"]["likeCount"])
        print (video_list_item["snippet"]["description"])
        print (video_list_item["snippet"]["publishedAt"])
        print (video_list_item["status"]["privacyStatus"])

相关问题