Get Json from query done in google with WebBrowser C #

1

I need to perform the following process, perform a google search and get the search information in Json format, how could I do this?

I tried the following way, I used the C # WebBrowser and I browsed www.google.com.br, until it worked, but I need to get this information as Title and Link from the results of this research, does anyone know which best way to do this?

NOTE: I can not use the google API, I need to do it by hand.

privatevoidbtnPesquisar_Click(objectsender,EventArgse){webBrowser.Navigate("www.google.com.br/search?q=" + txtPesquisa.Text);

        var document = webBrowser.Document;
    }
    
asked by anonymous 14.07.2017 / 01:01

1 answer

1

We all know that the result of the webBrowser will be an Html, so let's go through the html getting the elements that are needed, the divs in the case of google, which have the class 'g' indicating that it is a search result .

After having this element, just take the link, indicated by the tag and then we can get its properties.

Follow the code below:

Click:
webBrowser1.Navigate("https://www.google.com.br/search?num=100&q=carros");
  

Tip: Use the num parameter to get more results: search? num = 100 & q = [your search]

 private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        HtmlElementCollection divs = webBrowser1.Document.GetElementsByTagName("div");
        List<Resultados> resultados = new List<Resultados>();
        Resultados r;
        foreach (HtmlElement x in divs)
        {
            if (x.GetAttribute("className") == "g")
            {
                HtmlElement link = x.GetElementsByTagName("a")[0];
                r = new Resultados();
                r.Titulo = link.InnerText;
                r.Url = link.GetAttribute("href");
                resultados.Add(r);
            } 
        }

        int cout = resultados.Count; //Sua List com todos os resultados da pesquisa.

    }

    public class Resultados
    {
        public string Url { get; set; }
        public string Titulo { get; set; }
    }

Now json: I used the library Newtonsoft.Json

string json = "";
foreach (Resultado r in resultados)
    json+=  Newtonsoft.Json.JsonConvert.SerializeObject(r);


string seuJsonCompleto = json;
    
14.07.2017 / 01:40