我試圖運行Python代碼來使用YouTube生成的API密鑰來下載YouTube數據。我的問題是每當我嘗試運行代碼時,我都會收到警告和錯誤。當我從Coursera下載代碼時,該代碼曾經工作過一次,但是現在一旦它停止工作,我就得到了結果。獲取YouTube數據API的關鍵錯誤和Python代碼導入錯誤
此代碼的輸出是一個CSV文件,其中包含像like count,view count,comment count dislike count,favorite count等視頻數據,稍後我將使用它來對R或Python做一些統計分析,作爲我的Coursera課程。
PFB這是我使用的代碼:xxxxx是對我來說這是我從谷歌的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))
每當我運行代碼,我得到以下錯誤:
觀看次數= video_result [u'statistics'] [ 「觀看次數」]
KeyError異常: '統計'
警告:googleapiclient.discovery_cache:在使用oauth2client> 4.0.0時file_cache不可用 回溯(最近呼叫最後一次): 文件「C:\ Anaconda3 \ Anaconda3 4.2.0 \ lib \ site-packages \ googleapiclient \ discovery_cache__init__ py」爲,從google.appengine.api進口的memcache線36,在自動檢測 導入錯誤:沒有名爲模塊‘谷歌’
在處理上述異常,另一個異常:
回溯(最近最後呼叫): 文件「C:\ Anaconda3 \ Anaconda3 4.2.0 \ lib \ site-packages \ googleapiclient \ discovery_cache \ file_cache.py」,第33行,i ñ 從oauth2client.contrib.locked_file進口LockedFile 導入錯誤:沒有模塊名爲「oauth2client.contrib.locked_file
如何克服這個問題?
我試過video_result..get('Statistics'),但它沒有得到我所需的結果。代碼提前1-2次運行,沒有任何變化,當我下載它時給了我25個視頻結果(正如你可以在底部看到可以提取的結果的最大限度,我已將它們設置爲25),但由於某些原因,它現在停止工作。 – SidM