首页 > 解决方案 > 如何使用 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 示例。

我如何收到所有结果?


我一直面临的另一个“问题”是如何获取相同 JSON 的缩略图,因为显然它不起作用:

"thumbnail": search["items"][1]['volumeInfo']['imageLinks']['thumbnail']

标签: pythonjsongoogle-books-api

解决方案


您需要遍历响应以获取值。您可以将您的 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'])

推荐阅读