您的位置:首页 > 编程语言 > Go语言

Google Custom Search API的使用

2013-03-01 19:21 274 查看
本文将介绍如何使用GoogleCustom Search API,调用Google的搜索结果。最后提供了一个用PHP编写的简单示例。

一、获取Google的授权

1.注册Google帐号,网址链接:https://accounts.google.com/NewAccount
2.开启Custom Search功能:打开网址https://code.google.com/apis/console→在services菜单中开启Custom
Search API功能→ 在API Access菜单中获取相应的API
Key。
3.创建基于Google Custom Search的应用:打开网址http://www.google.com/cse/manage/create→填写表单并提交(Sites
to search一栏是Google搜索的网址,所以如果要搜索整个互联网,就需要将互联网所有网址输进去)→
获取应用的ID(即请求参数中的cx参数)。

二、Google Custom Search API使用流程

1.发送数据请求。Google Custom Search API的使用采用GET请求方式,请求的URL为https://www.googleapis.com/customsearch/v1?cx={APP
ID}&key={API Key}&q={key word}
其中还用得上的参数有start(返回的第一条搜索结果的标号,默认值是1)、num(一次返回的搜索结果条数,范围是1-10,默认是10)。具体的请求参数请参见链接https://developers.google.com/custom-search/v1/using_rest#st_params。
2.获取请求返回的结果。请求返回的结果有两种数据格式,JSON和Atom,默认情况下返回的是JSON格式的数据。
3.解析返回的结果。PHP、Python、Java等都有解析JSON的库文件,可以直接解析返回的搜索结果。

三、PHP调用Custom
Search API示例

<html>
<body>
<?php
// 初始化一个 cURL 对象
$curl = curl_init();
$key = '*******************************';
$cx = '********************************';
$q = 'english';
$url = 'https://www.googleapis.com/customsearch/v1?'.'cx='.$cx.'&key='.$key.'&q='.$q;
// 设置你需要抓取的URL
curl_setopt($curl, CURLOPT_URL, $url);
// 设置header
curl_setopt($curl, CURLOPT_HEADER, 0);
// 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 运行cURL,请求网页
$data = curl_exec($curl);
// 关闭URL请求
curl_close($curl);
// 显示获得的数据
//var_dump($data);
// Parse json data
$json = json_decode($data);
if(isset($json)) {
echo $json->items[0]->title;
} else {
echo 'json is null.';
}
?>
</body>
</html>


Reference

1.Google Custom Search的使用

2.Custom Search API Developer's Guide
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: