访问 API 数据并插入 CSV 文件时输入错误

问题描述 投票:0回答:1

我正在尝试使用 python 访问 api,从中提取指定的数据并将其添加到 csv 文件中的正确元素标题下。我不断收到错误:

name = item['name'] TypeError: string indices must be integers, not 'str'
对于第一个循环开头附近的行:.

我不知道我做错了什么:

import requests
import csv

from pprint import pprint as pp

aHeader = ['name', 'birth_year', 'height', 'mass']
with open('star_wars_people2.csv', 'w') as file:
    file = csv.DictWriter(file, fieldnames=aHeader)
    file.writeheader()


def get_info():
    for item in data:
        name = item['name']
        birth_year = item['birth_year']
        height = item['height']
        mass = item['mass']
        with open('star_wars_people2.csv', 'a') as aFile:
            aFile.write(name + birth_year + height + mass + "\n")


for i in range(5):
    user_input = input("Pick a number between 1 and 83 to find the associated Star Wars character: ")
    endpoint2 = 'https://swapi.dev/api/people/{}/'.format(user_input)
    response = requests.get(endpoint2)
    data = response.json()
    pp(data)

    user_input2 = input("Would you like to add this info to a file? ")
    if user_input2 == 'y' or 'Y':
        get_info()
    else:
        print('No problem!')

我对代码很陌生,但我注意到,当我定位整个 api 并使用下面的代码时,它可以定位一个特定元素 - 但我无法将其转换为指定一个页面并定位多个元素:

endpoint1 = 'https://swapi.dev/api/people/'
response = requests.get(endpoint1)
data = response.json()
pp(data)

aHeader = ['name', 'birth_year', 'height', 'mass']
with open('star_wars_people2.csv', 'w') as file:
    file = csv.DictWriter(file, fieldnames=aHeader)
    file.writeheader()


# def get_info():
for item in data['results']:
    with open('star_wars_people2.csv', 'a') as aFile:
        aFile.write(item['name'] + "\n")

python data-retrieval
1个回答
0
投票

首先,我认为您想将

data
作为参数传递给函数
def get_info():
,并在提示循环中将其称为
get_info(data)

您得到的错误意味着

item
变量不是您期望的类似字典的对象,而是字符串。
data
已经是您想要解析的对象,因此您不需要像
for item in data:
那样对其运行 for 循环。

def get_info(data):
    with open("star_wars_people2.csv", "a") as aFile:
        aFile.write(
            data["name"] + data["birth_year"] + data["height"] + data["mass"] + "\n"
        )
© www.soinside.com 2019 - 2024. All rights reserved.