如何使用适用于 .NET 的 Google 自定义搜索 API 进行搜索?

发布于 2024-12-14 06:53:24 字数 309 浏览 2 评论 0原文

我刚刚发现了适用于 .NET 的 Google API 客户端库,但是因为由于缺乏文档,我很难弄清楚。

我正在尝试通过进行自定义搜索来进行简单的测试,并且我还查看了以下命名空间:

Google.Apis.Customsearch.v1.Data.Query

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

I just discovered the Google APIs Client Library for .NET, but because of lack of documentation I have a hard time to figure it out.

I am trying to do a simple test, by doing a custom search, and I have looked among other, at the following namespace:

Google.Apis.Customsearch.v1.Data.Query

I have tried to create a query object and fill out SearchTerms, but how can I fetch results from that query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

莫言歌 2024-12-21 06:53:24

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

作为先决条件,您需要获取 Google API 客户端库

(特别是,您需要在项目中引用 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);
}

My bad, my first answer was not using the Google APIs.

As a pre-requisite, you need to get the Google API client library

(In particular, you will need to reference Google.Apis.dll in your project). Now, assuming you've got your API key and the CX, here is the same code that gets the results, but now using the actual APIs:

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);
}
眼泪都笑了 2024-12-21 06:53:24

首先,您需要确保已生成 API 密钥和 CX。我假设您已经这样做了,否则您可以在以下位置执行此操作:

  • API 密钥 (您需要创建一个新的浏览器密钥)
  • 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 反序列化为字典,而不是强类型。这是为了方便起见,因为我不想创建一个实现搜索结果架构的类。通过这种方法,有效负载是嵌套的键值对集。您最感兴趣的是项目集合,即搜索结果(我认为是第一页)。我仅访问“标题”和“链接”属性,但还有更多内容超出您从文档中看到或在调试器中检查的范围。

First of all, you need to make sure you've generated your API Key and the CX. I am assuming you've done that already, otherwise you can do it at those locations:

  • API Key (you need to create a new browser key)
  • CX (you need to create a custom search engine)

Once you have those, here is a simple console app that performs the search and dumps all the titles/links:

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();
    }
}

As you can see, I'm using a generic JSON deserialization into a dictionary instead of being strongly-typed. This is for convenience purposes, since I don't want to create a class that implements the search results schema. With this approach, the payload is the nested set of key-value pairs. What interests you most is the items collection, which is the search result (first page, I presume). I am only accessing the "title" and "link" properties, but there are many more than you can either see from the documentation or inspect in the debugger.

若能看破又如何 2024-12-21 06:53:24

请参阅 API 参考
使用 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

look at API Reference
using code from 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);

or

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);
}

with the stream you can also read off of webClient or HttpRequest, as you wish

把时间冻结 2024-12-21 06:53:24

您可以从API 入门开始。

you may start from Getting Started with the API.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文