How can I do a search with Google Custom Search API for .NET?

前端 未结 5 924
执笔经年
执笔经年 2021-01-01 00:49

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,

5条回答
  •  Happy的楠姐
    2021-01-01 01:50

    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 collection = serializer.Deserialize>(result);
        foreach (Dictionary 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.

提交回复
热议问题