Google Custom Search API:siteSearch多站点值传递返回空结果问题
问题解决:Google自定义搜索API多站点过滤返回空结果
问题原因
你当前代码里的siteSearch参数传递了列表类型,但Google Custom Search API的该参数仅支持字符串格式。当需要指定多个站点时,必须将多个域名用OR运算符拼接成单个字符串,API才能正确解析并在这些站点内检索内容。
修正后的代码
def search_restaurant(query): result_links = [] api_key = "" # 填入你的API密钥 search_engine_id = "" # 填入你的搜索引擎ID service = build('customsearch', 'v1', developerKey=api_key) # 将多个站点用OR拼接成字符串 res = service.cse().list( q=query, cx=search_engine_id, num=3, siteSearch="yelp.com OR tripadvisor.com OR usmenuguide.com" ).execute() print(res) if 'items' in res: for item in res['items']: result_links.append(item['link']) return result_links
额外说明
- 域名无需添加
http://或https://前缀,直接写主域名即可 - 如果需要排除某些站点,可以配合
siteSearchFilter参数设置为"e"(默认是"i"表示包含) - 确保你的自定义搜索引擎配置允许检索这些站点的内容,否则也可能返回空结果
内容的提问来源于stack exchange,提问作者hari ram
相关产品推荐
相关产品推荐

