Youtube API-python数据下载脚本错误

时间:2019-06-13 07:06:05

标签: python youtube-api youtube-analytics-api

我设法运行了一个部分脚本,用于通过API下载分析。 下面是我使用的代码。

from datetime import datetime, timedelta
import httplib2
import os
import sys

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

CLIENT_SECRETS_FILE = "client_secret.json"
#channel_id= "UCYdadasiio69NXxvhoPw"

YOUTUBE_SCOPES = [
    "https://www.googleapis.com/auth/youtube", 
    "https://www.googleapis.com/auth/youtube.readonly",
    "https://www.googleapis.com/auth/youtubepartner",
    "https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
    "https://www.googleapis.com/auth/yt-analytics.readonly"]
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
YOUTUBE_ANALYTICS_API_SERVICE_NAME = "youtubeAnalytics"
YOUTUBE_ANALYTICS_API_VERSION = "v1"
MISSING_CLIENT_SECRETS_MESSAGE = "credentials missed"

def get_authenticated_services(args):
    flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
        scope=" ".join(YOUTUBE_SCOPES),
        message=MISSING_CLIENT_SECRETS_MESSAGE)

    storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage, args)
    http = credentials.authorize(httplib2.Http())

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,http=http)
    youtube_analytics = build(YOUTUBE_ANALYTICS_API_SERVICE_NAME,
        YOUTUBE_ANALYTICS_API_VERSION, http=http)   

    return(youtube, youtube_analytics)

def get_channel_id(youtube):
    channels_list_response = youtube.channels().list(
        mine=True,
        part="id"
    ).execute()
    return channels_list_response["items"][0]["id"]


def run_analytics_report(youtube_analytics, channel_id, options):
  # Call the Analytics API to retrieve a report. For a list of available
  # reports, see:
  # https://developers.google.com/youtube/analytics/v1/channel_reports
  analytics_query_response = youtube_analytics.reports().query(
    ids="contentOwner==%s" % options.content_owner_id,
    filters="channel==%s" % options.channel_id,
    metrics=options.metrics,
    dimensions=options.dimensions,
    start_date=options.start_date,
    end_date=options.end_date,
    max_results=options.max_results,
    sort=options.sort
  ).execute()

print "Analytics Data for Channel %s" % channel_id
print analytics_query_response

for column_header in analytics_query_response.get("columnheaders", []):
    print "%-20s" % column_header["name"],

for row in analytics_query_response.get("rows", []):
    for value in row:
        print "%-20s" % value,


if __name__ == "__main__":
  now = datetime.now()
  one_day_ago = (now - timedelta(days=1)).strftime("%Y-%m-%d")
  one_week_ago = (now - timedelta(days=7)).strftime("%Y-%m-%d")

  argparser.add_argument("--metrics", help="Report metrics",
    default="views,earnings")
  argparser.add_argument("--dimensions", help="Report dimensions",
    default="video")
  argparser.add_argument("--start-date", default=one_week_ago,
    help="Start date, in YYYY-MM-DD format")
  argparser.add_argument("--end-date", default=one_day_ago,
    help="End date, in YYYY-MM-DD format")
  argparser.add_argument("--max-results", help="Max results", default=10)
  argparser.add_argument("--sort", help="Sort order", default="-views")
  args = argparser.parse_args()

  (youtube, youtube_analytics) = get_authenticated_services(args)
try:
  channel_id = get_channel_id(youtube)
  run_analytics_report(youtube_analytics, channel_id, args)
except HttpError, e:
  print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

不幸的是,授权在下载频道列表的情况下不起作用:

print "Analytics Data for Channel %s" % channel_id
NameError: name 'channel_id' is not defined

但是,如果我严格地传递chanell_id参数,则错误继续:

print analytics_query_response
NameError: name 'analytics_query_response' is not defined

以前,我的问题是使用新的python版本,现在我的版本是2.7.16

您能告诉我这些错误的原因是什么,因为我还没有想法吗?

我的意思是,尽管必须从yt下载数据,然后定义analytics_query_response的错误定义,但未定义使用变量在channel_id下载开始时会导致错误的原因是什么?

以下代码段存在问题: 1. channel_id

def get_channel_id(youtube):
    channels_list_response = youtube.channels().list(
        mine=True,
        part="id"
    ).execute()
    return channels_list_response["items"][0]["id"]
  1. analytics_query_response
def run_analytics_report(youtube_analytics, channel_id, options):
  # Call the Analytics API to retrieve a report. For a list of available
  # reports, see:
  # https://developers.google.com/youtube/analytics/v1/channel_reports
  analytics_query_response = youtube_analytics.reports().query(
    ids="contentOwner==%s" % options.content_owner_id,
    filters="channel==%s" % options.channel_id,
    metrics=options.metrics,
    dimensions=options.dimensions,
    start_date=options.start_date,
    end_date=options.end_date,
    max_results=options.max_results,
    sort=options.sort
  ).execute()

0 个答案:

没有答案