尝试通过 Youtube 数据 API V3 检索 youtube 评论时出现 AttributeError



我正在尝试使用Python检索YouTube视频的评论线程。大约两周来,我一直在打破大脑并在网上寻找解决方案,但似乎没有适合我的问题。我试图遵循 Youtube 数据 API 网站上的示例,但有时缺乏一点清晰度。特别是在使平台上的请求适应代码时。就我而言,我认为我的问题是由于我真的不知道什么对应于以下代码中的"youtube"对象。

import httplib2
import os
import sys
from apiclient.discovery import build_from_document
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the {{ Google Cloud Console }} at
# {{ https://cloud.google.com/console }}.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "../***************.json"
# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account and requires requests to use an SSL connection.
YOUTUBE_READ_WRITE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
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:
   %s
with information from the APIs Console
https://console.developers.google.com
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                               CLIENT_SECRETS_FILE))
# Authorize the request and store authorization credentials.
def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SSL_SCOPE,
    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)
  # Trusted testers can download this discovery document from the developers page
  # and it should be in the same directory with the code.
  with open("youtube-v3-discoverydocument.json", "r") as f:
    doc = f.read()
    return build_from_document(doc, http=credentials.authorize(httplib2.Http()))
# Call the API's commentThreads.list method to list the existing comments.
def get_comments(youtube, video_id, channel_id):
  results = youtube.commentThreads().list(
    part="snippet",
    videoId=video_id,
    channelId=channel_id,
    textFormat="plainText"
  ).execute()
  for item in results["items"]:
    comment = item["snippet"]["topLevelComment"]
    author = comment["snippet"]["authorDisplayName"]
    text = comment["snippet"]["textDisplay"]
    print "Comment by %s: %s" % (author, text)
  return results["items"]
get_comments("https://www.youtube.com/", "C_jByE6Cxv8", "UCww2zZWg4Cf5xcRKG-ThmXQ")

我不断得到一个 'str' 对象没有属性 'commentThreads'我想这不是我会遇到的唯一错误,但我无法超越这个错误,所以如果有人知道我为什么会收到此错误,或者如果有人看到代码中的任何其他错误,请告诉我。非常感谢Stackoverflow中的每个人,对于像我这样的新手来说,这是一个非常令人难以置信的网站。

我将回答为什么"Youtube对象"没有属性"commentThreads"的问题:

这是因为在 Youtube Data API V3 示例中(在 CLI 模式程序上唯一演示(,它们使用"youtube"来命名包含函数的变量,该函数通常是身份验证函数。这就是您收到该错误的原因。您正在尝试将属性添加到不存在的变量,而是添加到字符串对象。

您希望创建一个保存身份验证块的函数,然后创建一个名为"youtube"的变量,其中包含身份验证函数。然后它就会起作用。

我知道这些示例严格限于 CLI 风格的程序,对于新手来说很难遵循,但它非常值得投资。继续挖掘(c:

编辑:

为了使它更清楚一点(这只是伪代码供您理解(:

def get_auth():
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SSL_SCOPE,
    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)

youtube = get_auth()
youtube.commentThreads().list

然后,您基本上会将身份验证"粘合"到请求中。您基本上是在构建要发送到Youtube服务器的请求。问题是库在幕后为你做所有事情,除非你深入研究库代码,否则你无法真正看到发生了什么或它是如何工作的。您必须提高逆向工程技能才能揭穿 CLI 示例的谜语。

相关内容

  • 没有找到相关文章