You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google API进行相似图片搜索遇JSONDecodeError及400错误求助

问题排查与修复方案

核心问题分析

  • API端点错误:你使用的https://www.googleapis.com/customsearch/v1/similar不是Google Custom Search的合法端点,正确接口地址是https://www.googleapis.com/customsearch/v1。
  • 请求格式错误:直接POST二进制图片数据不符合API要求,相似图片搜索需要通过imgUpload参数以multipart/form-data格式上传图片,或使用公开图片URL通过imgSimilarTo参数指定。
  • 缺少必填参数:未指定searchType=image,这是获取图片搜索结果的强制参数。
  • 无错误处理:收到400错误响应后仍强行解析JSON,而400返回的是错误文本而非JSON结构,导致JSONDecodeError。

修复后的代码

import requests
import urllib.request
from urllib.parse import urlparse

# 替换为你的API密钥和自定义搜索引擎ID
api_key = "YOUR_API_KEY"
cx = "d47119ff66e004d6b"
image_path = "C:\\Users\\Administrator\\Downloads\\theme\\3f559715-f407-47de-8540-1cd9e4fdc56c.jpg"

# 构建请求参数
params = {
    "key": api_key,
    "cx": cx,
    "searchType": "image",  # 必须指定为图片搜索
    "imgType": "photo"  # 可选,过滤结果为照片类型
}

# 以multipart/form-data格式上传图片
with open(image_path, "rb") as image_file:
    files = {"imgUpload": image_file}
    response = requests.post(
        "https://www.googleapis.com/customsearch/v1",
        params=params,
        files=files
    )

# 先检查响应状态码
if response.status_code != 200:
    print(f"请求失败,状态码:{response.status_code}")
    print("错误信息:", response.text)
else:
    try:
        results = response.json().get("items", [])
        if not results:
            print("未找到相似图片")
        else:
            # 遍历结果下载图片
            for idx, result in enumerate(results):
                image_url = result["link"]
                # 生成安全的文件名(避免特殊字符问题)
                parsed_url = urlparse(image_url)
                filename = f"similar_image_{idx}_{parsed_url.path.split('/')[-1]}"
                # 下载图片
                try:
                    urllib.request.urlretrieve(image_url, filename)
                    print(f"已下载:{filename}")
                except Exception as e:
                    print(f"下载{image_url}失败:{str(e)}")
    except Exception as e:
        print(f"解析响应失败:{str(e)}")

额外注意事项

  • 确保你的Google Cloud账号已启用Custom Search API,且API密钥有足够权限。
  • 自定义搜索引擎ID(cx)需正确关联到你的搜索配置,确保允许图片搜索。
  • Google Custom Search API有调用配额限制,超出配额会返回429错误,需留意配额使用情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 10:40:51