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

Python调用Google自定义搜索API失败,提示请求参数无效

问题排查:Google自定义搜索API返回400无效参数错误

核心原因:num参数超出上限

Google Custom Search API的num参数最大允许值为10,你代码里设置了num_results = 100,直接违反API参数限制,触发badRequest错误。

解决方法

要获取100条结果,需通过分页实现:每次请求最多取10条,循环调用API并使用start参数偏移结果位置:

from googleapiclient.discovery import build

api_key = GOOGLE_SEARCH_KEY
search_engine_id = SEARCH_ENGINE_ID
query = "test"
total_results = 100
results_per_page = 10  # 必须≤10

service = build("customsearch", "v1", developerKey=api_key)
all_results = []

for start in range(1, total_results + 1, results_per_page):
    try:
        response = service.cse().list(
            q=query,
            cx=search_engine_id,
            num=results_per_page,
            start=start
        ).execute()
        all_results.extend(response.get('items', []))
    except Exception as e:
        print(f"请求失败(起始位置{start}): {e}")
        break

print(f"共获取到{len(all_results)}条结果")

额外注意事项

  • 单次分页请求的start参数不能超过100(API限制仅返回前100条结果)
  • 确保API密钥的配额足够支撑多次调用(100条结果需10次请求)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:30:28