首页 > 解决方案 > 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")

标签: pythonmysqlyoutube-api

解决方案


这里的响应是一本字典。因此,您首先必须使用 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']
    

推荐阅读