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
相关产品推荐
相关产品推荐

