【问题标题】:Getting key error and Import error in Python code for YouTube data API获取 YouTube 数据 API 的 Python 代码中的关键错误和导入错误
【发布时间】:2017-04-09 10:40:49
【问题描述】:

我正在尝试运行 Python 代码以使用为 YouTube 生成的 API 密钥下载 YouTube 数据。我的问题是每当我尝试运行代码时,我都会收到警告和错误。该代码在我从 Coursera 下载时运行过一次,但现在在它停止运行后得到结果。

此代码的输出是一个 CSV 文件,其中包含视频数据,例如计数、观看计数、评论计数、不喜欢计数、收藏计数等。我稍后将使用这些数据对 R 或 Python 进行一些统计分析,作为我的一部分Coursera 上的课程。

PFB 我使用的代码:xxxxx 是我从 Google YouTube 数据 API v3 生成的 API 密钥

Enter code here

# -*- coding: utf-8 -*-

from apiclient.discovery import build
#from apiclient.errors import HttpError
#from oauth2client.tools import argparser # removed by Dongho
import argparse
import csv
import unidecode

# Set DEVELOPER_KEY to the API key value from the APIs & authentication ? Registered apps
# tab of
#   https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = "xxxxxxxxxxxx"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def youtube_search(options):
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
    # Call the search.list method to retrieve results matching the specified
    # Query term.
    search_response = youtube.search().list(q=options.q, part="id,snippet", maxResults=options.max_results).execute()

    videos = []
    channels = []
    playlists = []

    # Create a CSV output for video list
    csvFile = open('video_result.csv','w')
    csvWriter = csv.writer(csvFile)
    csvWriter.writerow(["title","videoId","viewCount","likeCount","dislikeCount","commentCount","favoriteCount"])

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    for search_result in search_response.get("items", []):
        if search_result["id"]["kind"] == "youtube#video":
            #videos.append("%s (%s)" % (search_result["snippet"]["title"],search_result["id"]["videoId"]))
            title = search_result["snippet"]["title"]
            title = unidecode.unidecode(title)  # Dongho 08/10/16
            videoId = search_result["id"]["videoId"]
            video_response = youtube.videos().list(id=videoId,part="statistics").execute()
            for video_result in video_response.get("items",[]):
                viewCount = video_result["statistics"]["viewCount"]
                if 'likeCount' not in video_result["statistics"]:
                    likeCount = 0
                else:
                    likeCount = video_result["statistics"]["likeCount"]
                if 'dislikeCount' not in video_result["statistics"]:
                    dislikeCount = 0
                else:
                    dislikeCount = video_result["statistics"]["dislikeCount"]
                if 'commentCount' not in video_result["statistics"]:
                    commentCount = 0
                else:
                    commentCount = video_result["statistics"]["commentCount"]
                if 'favoriteCount' not in video_result["statistics"]:
                    favoriteCount = 0
                else:
                    favoriteCount = video_result["statistics"]["favoriteCount"]

            csvWriter.writerow([title,videoId,viewCount,likeCount,dislikeCount,commentCount,favoriteCount])

    csvFile.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Search on YouTube')
    parser.add_argument("--q", help="Search term", default="Google")
    parser.add_argument("--max-results", help="Max results", default=25)
    args = parser.parse_args()
    #try:
    youtube_search(args)
    #except HttpError, e:
    #    print ("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))

每当我运行代码时,都会出现以下错误:

  1. viewCount = video_result[u'statistics']["viewCount"]

    KeyError: '统计'

  2. 警告:googleapiclient.discovery_cache:file_cache 在使用 oauth2client >= 4.0.0 时不可用 回溯(最近一次通话最后): 自动检测中的文件“C:\Anaconda3\Anaconda3 4.2.0\lib\site-packages\googleapiclient\discovery_cache__init__.py”,第 36 行 从 google.appengine.api 导入内存缓存 ImportError:没有名为“google”的模块

    在处理上述异常的过程中,又发生了一个异常:

    Traceback(最近一次调用最后一次): 文件“C:\Anaconda3\Anaconda3 4.2.0\lib\site-packages\googleapiclient\discovery_cache\file_cache.py”,第 33 行,在 从 oauth2client.contrib.locked_file 导入 LockedFile ImportError:没有名为“oauth2client.contrib.locked_file”的模块

我该如何克服这个错误?

【问题讨论】:

    标签: python youtube youtube-data-api spyder


    【解决方案1】:

    您能否检查一下您是否将统计信息作为 video_result 中的键。当您尝试访问不存在的 Python Dict 中的键时,会发生 KeyError。因此,更好的方法是在查找密钥时使用“get()”, 例如:video_result.get('statistics') 这将处理您的关键错误。 第二个错误是由于缺少导入语句而出现的。该文件无法导入导入的文件/函数,这就是它在报告异常时抛出异常的原因。

    【讨论】:

    • 我试过 video_result..get('Statistics') 但它没有让我得到所需的结果。当我下载它并给我 25 个视频结果时,代码在没有任何更改的情况下运行了 1-2 次(正如您在底部看到的可以提取的结果的最大限制,我已将它们设置为 25)但由于一些原因,它现在停止工作了。
    猜你喜欢
    • 2012-03-17
    • 2019-08-17
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多