How to get top answer from google search in my app

2.5k views Asked by At

I want to develop a desktop application using (any programming language)C#.NET; the requirement is to show the answer to a question in a text view as Google does when someone searches any question like shown in the image.

I want to extract the text in bold from Google search so that I can store that in my app and show the user the result in my app

Google Top Search Result

1

There are 1 answers

0
pio On

There are 2 options for it:

1. HTML parsing

You need to get the HTML code, then process it to find the signiture of the so called "top results".

You can use code like this example to get the HTML code:

string urlAddress = "https://www.google.co.il/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=what%20is%20the%20weight%20of%20human%20heart";
// need to process to get the real URL of the question.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (response.CharacterSet == null)
  {
     readStream = new StreamReader(receiveStream);
  }
  else
  {
     readStream = new StreamReader(receiveStream,Encoding.GetEncoding(response.CharacterSet));
  }

  string data = readStream.ReadToEnd();
  response.Close();
  readStream.Close();
}

This will give you the returned HTML code from the website.

To extract of the top result you can use some HTML parser like discussed here: What is the best way to parse html in C#?

2. GOOGLE API

You can also use the google API:

using Google.API.Search;

and then

 var client = new GwebSearchClient("http://www.google.com");
    var results = client.Search("google api for .NET", 100);
    foreach (var webResult in results)
    {
        //Console.WriteLine("{0}, {1}, {2}", webResult.Title, webResult.Url, webResult.Content);
        listBox1.Items.Add(webResult.ToString ());
    }