如何使用适用于 .NET 的 Google 自定义搜索 API 进行搜索?
我刚刚发现了适用于 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不好的是,我的第一个答案是不使用 Google API。
作为先决条件,您需要获取 Google API 客户端库
(特别是,您需要在项目中引用 Google.Apis.dll)。现在,假设您已获得 API 密钥和 CX,下面是获取结果的相同代码,但现在使用实际的 API:
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:
首先,您需要确保已生成 API 密钥和 CX。我假设您已经这样做了,否则您可以在以下位置执行此操作:
一旦您有了这些,这是一个简单的控制台应用程序,它执行搜索并转储所有内容标题/链接:
如您所见,我使用通用 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:
Once you have those, here is a simple console app that performs the search and dumps all the titles/links:
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.
请参阅 API 参考
使用 google-api-dotnet-client 中的代码
或
通过流,您还可以根据需要读取
webClient
或HttpRequest
look at API Reference
using code from google-api-dotnet-client
or
with the stream you can also read off of
webClient
orHttpRequest
, as you wishGoogle.Apis.Customsearch.v1 客户端库
http://www.nuget.org/packages/Google.Apis.Customsearch。 v1/
Google.Apis.Customsearch.v1 Client Library
http://www.nuget.org/packages/Google.Apis.Customsearch.v1/
您可以从API 入门开始。
you may start from Getting Started with the API.