【问题标题】:Goodreads API Error: List Indices must be integers or slices, not strGoodreads API 错误:列表索引必须是整数或切片,而不是 str
【发布时间】:2019-06-26 02:31:18
【问题描述】:

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

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

main.py

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"]))

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

Here 是 Goodreads 提供的示例 XML 文件。

【问题讨论】:

    标签: python json api dictionary python-requests


    【解决方案1】:

    我认为您对 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"] 是响应中所有书籍的集合(所有由&lt;book&gt; 标签包围的元素)。所以:

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

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

    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
    

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 1970-01-01
      • 2021-07-07
      • 2017-10-09
      • 2015-12-09
      • 2021-09-01
      • 2021-11-28
      • 1970-01-01
      相关资源
      最近更新 更多