如何使用Google Custom Search API for .NET进行搜索?

时间:2011-11-07 18:23:09

标签: api google-api

我刚刚发现了Google APIs Client Library for .NET,但由于缺乏文档,我很难弄明白。

我正在尝试进行一项简单的测试,通过自定义搜索,我在以下命名空间中查看了其他内容:

Google.Apis.Customsearch.v1.Data.Query

我尝试创建查询对象并填写SearchTerms,但如何从该查询中获取结果?

5 个答案:

答案 0 :(得分:7)

我的不好,我的第一个答案是没有使用Google API。

作为先决条件,您需要获得Google API client library

(特别是,您需要在项目中引用Google.Apis.dll)。现在,假设您已获得API密钥和CX,这里的代码与获取结果的代码相同,但现在使用实际的API:

string apiKey = "YOUR KEY HERE";
string cx = "YOUR CX HERE";
string query = "YOUR SEARCH HERE";

Google.Apis.Customsearch.v1.CustomsearchService svc = new Google.Apis.Customsearch.v1.CustomsearchService();
svc.Key = apiKey;

Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
Google.Apis.Customsearch.v1.Data.Search search = listRequest.Fetch();

foreach (Google.Apis.Customsearch.v1.Data.Result result in search.Items)
{
    Console.WriteLine("Title: {0}", result.Title);
    Console.WriteLine("Link: {0}", result.Link);
}

答案 1 :(得分:4)

首先,您需要确保已生成API密钥和CX。我假设你已经这样做了,否则你可以在那些地方做到这一点:

  • API Key(您需要创建新的浏览器密钥)
  • CX(您需要创建自定义搜索引擎)

有了这些,这是一个简单的控制台应用程序,执行搜索并转储所有标题/链接:

static void Main(string[] args)
{
    WebClient webClient = new WebClient();

    string apiKey = "YOUR KEY HERE";
    string cx = "YOUR CX HERE";
    string query = "YOUR SEARCH HERE";

    string result = webClient.DownloadString(String.Format("https://www.googleapis.com/customsearch/v1?key={0}&cx={1}&q={2}&alt=json", apiKey, cx, query));
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    Dictionary<string, object> collection = serializer.Deserialize<Dictionary<string, object>>(result);
    foreach (Dictionary<string, object> item in (IEnumerable)collection["items"])
    {
        Console.WriteLine("Title: {0}", item["title"]);
        Console.WriteLine("Link: {0}", item["link"]);
        Console.WriteLine();
    }
}

正如您所看到的,我将通用JSON反序列化用于字典而不是强类型。这是为了方便起见,因为我不想创建实现搜索结果模式的类。使用此方法,有效负载是嵌套的键值对集。你最感兴趣的是项目集合,这是搜索结果(第一页,我推测)。我只访问“标题”和“链接”属性,但是除了文档或在调试器中检查之外,还有很多其他内容。

答案 2 :(得分:2)

看看API Reference 使用google-api-dotnet-client

中的代码
CustomsearchService svc = new CustomsearchService();

string json = File.ReadAllText("jsonfile",Encoding.UTF8);
Search googleRes = null;
ISerializer des = new NewtonsoftJsonSerializer();
googleRes = des.Deserialize<Search>(json);

CustomsearchService svc = new CustomsearchService();

Search googleRes = null;
ISerializer des = new NewtonsoftJsonSerializer();
using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    googleRes = des.Deserialize<Search>(fileStream);
}

使用您也可以根据需要从webClientHttpRequest读取

答案 3 :(得分:1)

Google.Apis.Customsearch.v1客户端库 http://www.nuget.org/packages/Google.Apis.Customsearch.v1/

答案 4 :(得分:0)

您可以从Getting Started with the API开始。

相关问题