首页 > 解决方案 > Goodreads API 错误:列表索引必须是整数或切片,而不是 str

问题描述

因此,我正在尝试使用 Goodreads 的 API 在 Python 中编写 Goodreads Information Fetcher 应用程序。我目前正在开发应用程序的第一个函数,该函数将从 API 获取信息,API 返回一个 XML 文件。

我解析了 XML 文件并将其转换为 JSON 文件,然后进一步将其转换为字典。但我似乎仍然无法从中提取信息,我在这里查找了其他帖子,但没有任何效果。

主文件

def get_author_books(authorId):
    url = "https://www.goodreads.com/author/list/{}?format=xml&key={}".format(authorId, key)
    r = requests.get(url)

    xml_file = r.content
    json_file = json.dumps(xmltodict.parse(xml_file))

    data = json.loads(json_file)
    print("Book Name: " + str(data[0]["GoodreadsResponse"]["author"]["books"]["book"]))

我希望输出能给我字典中第一本书的名字。

是 Goodreads 提供的示例 XML 文件。

标签: pythonjsonapidictionarypython-requests

解决方案


我认为您对 xml 的工作原理缺乏了解,或者至少对您获得的响应的格式不了解。

您链接到的 xml 文件具有以下格式:

<GoodreadsResponse>
    <Request>...</Request>
    <Author>
        <id>...</id>
        <name>...</name>
        <link>...</link>
        <books>
            <book> [some stuff about the first book] </book>
            <book> [some stuff about the second book] </book>
            [More books]
        </books>
    </Author>
</GoodreadsResponse>

这意味着在您的data对象中,是响应中所有书籍的集合(所有被标签data["GoodreadsResponse"]["author"]["books"]["book"]包围的元素)。<book>所以:

  • data["GoodreadsResponse"]["author"]["books"]["book"][0]是第一本书。
  • data["GoodreadsResponse"]["author"]["books"]["book"][1]是第二本书,以此类推。

回顾 xml,每个book元素都有一个id, isbn, title,description等标签。所以你可以通过打印来打印第一本书的标题:

data["GoodreadsResponse"]["author"]["books"]["book"][0]["title"]

作为参考,我正在使用您链接到的 xml 文件运行以下代码,您通常会从 API 中获取它:

import json
import xmltodict

f = open("source.xml", "r") # xml file in OP
xml_file = f.read()

json_file = json.dumps(xmltodict.parse(xml_file))
data = json.loads(json_file)

books = data["GoodreadsResponse"]["author"]["books"]["book"] 

print(books[0]["title"]) # The Cathedral & the Bazaar: Musings on Linux and Open Source by an Accidental Revolutionary

推荐阅读