所以我正在做一个Youtube API项目,需要搜索电影。它连接到我的mySQL数据库,称为moviereviews。我有一个名为films的表,表中有一些列,如“title”或“description”等,您将在我的代码中看到这些列。我需要运行我的Python代码,以便将已插入mySQL数据库的记录。我得到一个字符串索引错误,所以我需要帮助如何修复它。我目前只能运行一部电影,但需要为我的项目运行3部。我也不知道在我出现当前错误之后,我的代码的其余部分是否正确。取出了我的api密钥。希望我能得到一些帮助,谢谢
import mysql.connector
from googleapiclient.discovery import build
api_key = ''
youtube = build('youtube', 'v3', developerKey=api_key)
moviereview = youtube.search().list(q="Tenet - Movie Review", part="id,snippet", type='video', maxResults=0, pageToken=None)
response = moviereview.execute()
mydb = mysql.connector.connect(host='localhost',
user='kkkoenn',
password='onnnnnoo',
database = "moviereview"
)
mycursor = mydb.cursor()
for movie in response:
title = movie['title'] #"this is where I am getting the error"
description = movie['description']
frame = movie['thumbnails']
releaseDate = movie['publishDate']
channel = movie['channelTitle']
sql = "INSERT INTO films (Title, Description, Frame, ReleaseDate, Channel) VALUES (%s, %s, %s, %s, %s)"
val = (title, description, frame, releaseDate, channel)
mycursor.execute(sql, val)
mydb.commit()
print("records inserted")
这是一本字典。因此,您首先必须使用
response ['items']
。然后您可以首先打印每个项目并检查项目本身的属性最好使用
.get
方法访问任何具有默认值的对象,以避免出现任何包含错误。示例:response.get('items', [])
相关问题 更多 >
编程相关推荐