You need to enable JavaScript to run this app. 如何使用Google Books API返回多本图书结果并获取封面缩略图
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Google Books API返回多本图书结果并获取封面缩略图

问题解决方法

一、多本图书搜索结果获取

错误原因

你原来的代码仅取了search["items"]数组的第0个元素(search["items"][0]),所以只能返回第一条结果。你后续修改的写法直接对数组类型的search["items"]调用['volumeInfo'],不符合Python语法,会触发KeyError被异常捕获,所以返回None。

修复代码

import requests

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:
        res_data = response.json()
        # 遍历所有item,整理每本图书的信息
        book_list = []
        for item in res_data.get("items", []):
            volume_info = item.get("volumeInfo", {})
            book_list.append({
                "title": volume_info.get("title"),
                "authors": volume_info.get("authors"),
                # 这里同时兼容处理缩略图字段
                "thumbnail": volume_info.get("imageLinks", {}).get("thumbnail")
            })
        return {
            "totalItems": int(res_data.get("totalItems", 0)),
            "books": book_list
        }
    except (KeyError, TypeError, ValueError):
        return None

二、缩略图获取失败问题

错误原因

两个常见触发场景:

  1. 部分图书的volumeInfo下没有imageLinks字段,或者imageLinks下没有thumbnail字段,直接按层级取会触发KeyError
  2. 你固定写死取索引为1的元素(search["items"][1]),如果API返回的结果不足2条,会触发数组越界错误

修复方案

上面的代码已经做了兼容处理:用字典的get()方法取值,对应字段不存在时会返回None不会抛出异常,你可以根据业务需要把None替换为默认的占位图地址。

内容的提问来源于stack exchange,提问作者ARNON

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 19:36:11