Google自定义搜索JSON API允许开发者通过HTTP协议向Google搜索引擎提交查询请求,并获取结构化的搜索结果数据。本指南将详细介绍如何使用该API。
此API无需安装,仅需获取API密钥即可使用。
以下是使用该API的基本步骤:
https://www.googleapis.com/customsearch/v1?q={搜索词}&key={API密钥}
其中:
q:必填参数,表示要查询的内容。key:必填参数,用于身份验证。https://www.googleapis.com/customsearch/v1?q=人工智能&key=你的API密钥
{
"items": [
{
"title": "标题", // 文章标题
"link": "链接地址", // URL链接
"snippet": "摘要" // 摘要描述
},
...
]
}
cx:网站搜索上下文ID,用于指定特定的Google Custom Search引擎。num:每页返回的结果数,默认为10。start:结果偏移量,用于分页查询。gl:国家代码,限制搜索区域。hl:语言代码,限定返回结果的语言。以下是一个简单的Python调用示例:
import requests
def custom_search(query, api_key):
url = "https://www.googleapis.com/customsearch/v1"
params = {
'q': query,
'key': api_key
}
response = requests.get(url, params=params)
return response.json()
# 使用示例
result = custom_search("人工智能", "你的API密钥")
print(result)
如需了解更多详细信息,请参阅官方文档: Custom Search JSON API Documentation
Google会对API调用次数进行限制,具体取决于使用的项目级别。
建议在代码中添加异常捕捉机制,确保程序健壮性。
使用该API必须遵守Google的Terms of Service。
⚠️ 重要提示
API密钥用于身份验证,请妥善保管。
💡 使用建议
建议在代码中添加异常捕捉机制,确保程序健壮性。同时,注意Google对API调用次数的限制。