python - Youtube API Python 和 mySQL。TypeError:字符串索引必须是整数。怎么修?
问题描述
所以我正在为 Youtube API 做一个项目,需要搜索电影。它连接到我称为moviereviews 的mySQL 数据库。我有一个名为电影的表,并且在该表中有列,例如“标题”或“描述”等,您将在我的代码中看到这些列。我需要运行我的 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', [])
movies = response.get('items', [])
for movie in movies:
print(movie)
print(type(movie))
title = movie['title'] # or equivalent movie.get('title', None) would work
description = movie['description']
frame = movie['thumbnails']
releaseDate = movie['publishDate']
channel = movie['channelTitle']
推荐阅读
- batch-file - 如何使用批处理文件查找当前正在运行的同名进程
- c++ - QScintilla:如何将用户上下文菜单添加到 textEdit?(C++)
- opengl - 如何将 gfx-rs (opengl) 场景渲染到 ImGui-rs 窗口中?
- sapui5 - 第 9 步的 openUI5 中缺少 index.js 文件:组件配置
- javascript - 如何从字节数组创建示例 webm 文件
- html - 附加导航栏跳转
- flutter - Flutter 1.0 - 无法加载文本资源
- tensorflow - 无法一次检测多个人脸
- string - 是否存在 unicode "New-Line" (换行符),就像有 unicode `space` ( )?
- bootstrap-4 - Electron 中的引导选项卡 - 我错过了什么?