python - 如何使用 Google Books API 返回包含多本书的搜索结果?
问题描述
我正在使用 Google Books API,并且正在尝试返回包含多本书的搜索结果。这就是我正在做的事情:
def lookup(search):
"""Look up search for books."""
# Contact API
try:
url = f'https://www.googleapis.com/books/v1/volumes?q={search}&key=myAPIKey'
response = requests.get(url)
response.raise_for_status()
except requests.RequestException:
return None
# Parse response
try:
search = response.json()
return {
"totalItems": int(search["totalItems"]),
"title": search["items"][0]['volumeInfo']['title'],
"authors": search["items"][0]['volumeInfo']['authors'],
}
except (KeyError, TypeError, ValueError):
return None
当然,这只返回一个结果。但是,如果我尝试这样称呼它:
"title": search["items"]['volumeInfo']['title']
它不返回任何东西。
我如何收到所有结果?
我一直面临的另一个“问题”是如何获取相同 JSON 的缩略图,因为显然它不起作用:
"thumbnail": search["items"][1]['volumeInfo']['imageLinks']['thumbnail']
解决方案
您需要遍历响应以获取值。您可以将您的 try: 更改为以下内容,这将提供标题和作者列表。如果你想要一些不同的东西,你可以适应它。
try:
search = response.json()
titles = []
authors = []
for itm in search['items']:
titles.append(itm['volumeInfo']['title'])
authors.append(itm['volumeInfo']['authors'])
return {
"totalItems": int(search["totalItems"]),
"title": titles,
"authors": authors,
}
像这样捕获的缩略图:
thumbnails = []
for itm in search['items']:
thumbnails.append(itm['volumeInfo']['imageLinks']['thumbnail'])
推荐阅读
- javascript - 如何使状态栏看起来像 HTML/CSS/JavaScript 中的某些在线订购状态栏?
- arrays - 根据matlab中的字典将一串字符转换为数字数组
- python - 如何在 Python3 中的函数中获取多个参数的用户输入
- javascript - 如何在一个 HTML 页面上的两个 Tabulator 表中显示一个 json 文件?
- azure - Azure 函数中的并发与 .Net 5(隔离)
- python-3.x - Python Selenium 按类名查找元素不起作用,并且在引发的错误中名称字符串的 0 位置有一个无条件点
- php - 比较来自 sql 数据库和 PHP 中 .xls 文件的两个西里尔字母字符串是否相等
- animation - Framer 运动复杂滚动动画
- java - 在 java 中使用多个线程安全地编辑数据库
- c# - 从内存流 C# 下载 Excel 文件