2017-04-09 14 views
0

YouTube向けに生成されたAPIキーを使用してPythonコードを実行してYouTubeデータをダウンロードしようとしています。私の問題は、私が警告とエラーを取得しているコードを実行しようとするたびにです。このコードは、私がCourseraからダウンロードしたときに一度しか動作しませんでしたが、今度は動作が停止してから結果が得られます。YouTubeデータ用Pythonコードのキーエラーおよびインポートエラーの取得

このコードの出力は、後でRまたはPythonの一部として統計分析を行うために使用する、カウント、ビュー数、コメント数、嫌いカウントなどのビデオデータを含むCSVファイルです。コースラの私のコース。

PFB私が使用したコード:

  1. :xxxxxは、私は、コードを実行するたびに

    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)) 
    

    は、私は次のエラーを取得し、私はGoogleのYouTubeのデータAPI v3のから生成された私のためのAPIキーです

    再生回数= video_result [u'statistics'] [ "再生回数"]

    KeyError例外: '統計'

  2. 警告:googleapiclient.discovery_cache:oauth2client> = 4.0.0を使用している場合、file_cacheは使用できません。 トレースバック(最新のコール最後): ファイル "C:\ Anaconda3 \ Anaconda3 4.2.0 \ lib \ site-packages \ googleapiclient \ discovery_cache__init__ google.appengine.api輸入memcacheの はImportErrorから自動検出 での.py」、行36、:上記の例外の取り扱い中

    を 'GOOGLE' という名前のないモジュール、別の例外が発生しました:

    トレースバック(最新最後の呼び出し): ファイル "C:\ Anaconda3 \ Anaconda3 4.2.0 \ lib \ site-packages \ googleapiclient \ discovery_cache \ file_cache.py"、33行目、i n個oauth2client.contrib.locked_fileインポートLockedFile はImportErrorから :

oauth2client.contrib.locked_file」という名前のないモジュールは、どのように私はこのエラーを克服していますか?

答えて

0

統計情報をキーとして使用しているかどうかを確認するには、video_resultでご確認ください。 KeyErrorは、存在しないPython Dictのキーにアクセスしようとすると発生します。したがって、より良い方法は、キーを探しているときに 'get()'を使うことです。 例:video_result.get( 'statistics') これはあなたにキーエラーを処理します。 2番目のエラーは、インポートステートメントがないために発生しています。ファイルはインポートされたファイル/関数をインポートできません。そのため、例外を報告している間に例外をスローしています。

+0

私はvideo_result..get( 'Statistics')を試しましたが、必要な結果が得られませんでした。コードは、ダウンロードしたときに何も変更せずに1〜2回早く実行され、25のビデオ結果を得ました(抽出できる最大限の結果の下限を25に設定しています)が、理由は、今働いていない。 – SidM

関連する問題