python - 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 文件。
解决方案
我认为您对 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
推荐阅读
- linux - 在 Linux 上通过 OpenSSH 公钥身份验证使用 Powershell 更新 DNS
- javascript - 触发 3cx-clicktotalk WordPress 插件的 3cx 调用按钮
- android - 尝试使用 maven 和插件 com.jayway.maven.plugins.android.generation2 构建 android 应用程序时出现 NullPointerException
- sql - 将列名的文本值转换为查询中的列
- javascript - 如何为开放图层中的开放街道地图使用不同的主题?
- java - 列表上的 Selenium 非确定性循环
- java - Eclipse:导出具有依赖项的 java 库
- java - 声明和直接归因之间的区别
- azure - Microsoft.Azure.Cosmos SDK 带有延续令牌的分页查询
- python - 在 pytest 中重命名参数化测试