[英]Goodreads API Error: List Indices must be integers or slices, not str
因此,我正在嘗試使用Goodreads的API在Python中編寫Goodreads Information Fetcher App。 我目前正在開發該應用程序的第一個功能,該功能將從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"]))
我希望輸出能給我字典中第一本書的名字。
這是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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.