Google ha introdotto negli ultimi tempi una interessante funzionalità che ha battezzato con il nome di Google Suggest. Mountain View ha fatto un ottimo lavoro anche questa volta: certe volte sembra addirittura che la funzione legga nel pensiero.
Vediamo quindi come ottenere queste informazioni tramite un client scritto in VB.NET (facilmente traducibile in C#).
Creeremo un’applicazione ad interfaccia grafica. I controlli da aggiungere alla nostra form sono:
- txtQuery – Textbox in cui inserire i termini di ricerca
- lstSuggestions – ListBox che conterrà i risultati
- bgWorker – BackgroundWorker per rendere asincrono il processo di scaricamento
Ecco qua la funzione che rappresenta il cuore del programma:
Public Function GetGoogleSuggest(ByVal query As String, ByVal count As Integer, ByVal lang As String) As String() Dim xmldoc As New XmlDataDocument Dim suggArList As New List(Of String) Dim url As String = "http://google.com/complete/search?output=toolbar&hl=" & lang & "&q=" & query Dim node As XmlNode xmldoc.Load(url) Dim value As String For Each node In xmldoc.SelectNodes("//CompleteSuggestion") value = node.SelectSingleNode("suggestion/@data").InnerText suggArList.Add(value) If suggArList.Count = count Then Exit For End If Next Return suggArList.ToArray End Function
Possiamo notare che aprendo ad esempio l’indirizzo http://google.com/complete/search?output=toolbar&hl=it&q=test nel nostro browser otteniamo un documento XML contenente 10 nodi principali attinenti alla chiave di ricerca “test”. Il codice non fa altro che leggere queste informazioni ed inserirle in un array.
Scriviamo adesso il codice per il download asincrono:
Delegate Sub SetCompleteItemsCallback(ByVal arr() As String) Private Sub SetCompleteItems(ByVal arr() As String) If Me.txtQuery.InvokeRequired Then Dim d As New SetCompleteItemsCallback(AddressOf SetCompleteItems) Me.Invoke(d, New Object() {arr}) Else For Each item As String In arr lstSuggestions.Items.Add(item) Next End If End Sub Private Sub txtQuery_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtQuery.TextChanged lstSuggestions.Items.Clear() If bgWorker.IsBusy = False Then bgWorker.RunWorkerAsync() End If End Sub Private Sub bgWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork SetCompleteItems(GetGoogleSuggest(txtQuery.Text, -1, "it")) End Sub
Questo è tutto, credo che non ci sia altro da commentare.