我正在尝试运行python代码,这将有助于我从YouTube数据API v3连接和提取数据。但是,当我尝试运行代码时,它在第一行给了我以下错误:
File "C:/Users/asaxena/Desktop/py4e/Social Media Data Analytics/youtube_search.py", line 3, in <module>
from apiclient.discovery import build
ModuleNotFoundError: No module named 'apiclient'
我已经通过以下命令在工作目录中安装了google-api-python-client:pip install --upgrade google-api-python-client 但这并不能帮助我运行代码。
from apiclient.discovery import build
import argparse
import csv
import unidecode
def youtube_search(options):
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
search_response = youtube.search().list(q=options.q, part="id,snippet", maxResults=options.max_results).execute()
videos = []
channels = []
playlists = []
csvFile = open('video_result.csv','w')
csvWriter = csv.writer(csvFile)
csvWriter.writerow(["title","videoId","viewCount","likeCount","dislikeCount","commentCount","favoriteCount"])
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
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()
最后,我应该能够与YouTube数据API v3建立成功的连接,并将数据提取到csv文件中。
答案 0 :(得分:1)
我解决了:
我在工作目录中分别手动安装了“ google-api-python-client-master”,然后从命令行运行:“ setup.py install”。
然后我在解压后的“ google-api-python-client-master”文件夹中分别手动安装“ Unidecode-master”,然后从命令行运行:“ setup.py install”。
然后我运行了上面的代码,它成功了。
我认为您必须单独安装API文件夹,否则将无法正常工作。希望这是有用的。
答案 1 :(得分:0)
您正在导入不存在的模块。根据{{3}}文档,您应该使用:
from googleapiclient.discovery import ...
代替:
from apiclient.discovery import ...